title: Using XNA GameComponents simply

text:
# Question
Title: Using XNA GameComponents simply
looking for a quick code example (im a visual guy) and this is getting a little confusing/frustrating.

Because im a very "modular" kind of guy, I like to split my code up into logical files as often as possible, and all examples in the XNA tutorials led me into a small funk as all I ever did seemingly happened in the main .cs file save for my typical classes but all rendering takes in (example) Game1.cs so far.

I then heard about GameComponents and see they have the exact same structure as "Game1.cs", So I immediately set out to migrate my player code (it's not much) over to it, and it compiles correctly, but I honestly have NO idea how to implement the new component into my game.

So I made a new `GameComponentCollection` but when I try to add my new GameComponent class (extends `DrawableGameComponent` btw as you will see) with `components.Add` it simply tells me that I cannot.

Im not sure where to go from here to be honest, MSDN is useless with this topic (theres no documentation nor examples) and thread after thread has lead to very elaborate and very strange places that I would rather not get into. This seems like it should be a very simple concept, please correct me if im wrong here:

1. You create a new GameComponentCollection manager
2. You add your GameComponents and DrawableGameComponents to the manager
3. You do *something* with the manager (I'm not sure at this point, iterate through and call their updates?)

Need some help, heres my source code to this

Game1.cs

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Diagnostics;

namespace TestGame1
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GameComponentCollection components;
        DrawableGameComponent player;
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            player = new GC_Player( this );
            components.Add(player); // DOESN'T WORK. NullReferenceException

        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();

        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <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)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();

            spriteBatch.End();
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

```

GC\_Player.cs

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace TestGame1
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class GC_Player : Microsoft.Xna.Framework.DrawableGameComponent
    {

        King theKing;
        SpriteBatch spriteBatch;

        public GC_Player(Game game)
            : base(game)
        {
            // TODO: Construct any child components here
            // Make THE KING.
            theKing = new King();
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization code here

            base.Initialize();
        }

        protected override void LoadContent()
        {
            base.LoadContent();
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);

            theKing.Sprite = Game.Content.Load<Texture2D>("King");
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here

            UpdateSprite(gameTime);

            base.Update(gameTime);
        }

        void UpdateSprite(GameTime gameTime)
        {
            //spritePosition += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
            //theKing.Position = theKing.Position += theKing.Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;

            //int MaxX = Game.graphics.GraphicsDevice.Viewport.Width - theKing.SpriteWidth;
            int MinX = 0;
            //int MaxY = Game.graphics.GraphicsDevice.Viewport.Height - theKing.SpriteHeight;
            int MinY = 0;

            if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                theKing.SpeedVertical += theKing.AccelerationVertical;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                theKing.SpeedVertical -= theKing.AccelerationVertical;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                theKing.SpeedHorizontal += theKing.AccelerationHorizontal;
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                theKing.SpeedHorizontal -= theKing.AccelerationHorizontal;
            }
            if (Keyboard.GetState().IsKeyUp(Keys.Down) && Keyboard.GetState().IsKeyUp(Keys.Up))
            {
                if (theKing.SpeedVertical > 0)
                {
                    theKing.SpeedVertical -= theKing.AccelerationVertical;
                }
                else if (theKing.SpeedVertical < 0)
                {
                    theKing.SpeedVertical += theKing.AccelerationVertical;
                }
            }
            if (Keyboard.GetState().IsKeyUp(Keys.Left) && Keyboard.GetState().IsKeyUp(Keys.Right))
            {
                if (theKing.SpeedHorizontal > 0)
                {
                    theKing.SpeedHorizontal -= theKing.AccelerationHorizontal;
                }
                else if (theKing.SpeedHorizontal < 0)
                {
                    theKing.SpeedHorizontal += theKing.AccelerationHorizontal;
                }
            }

        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
            spriteBatch.Begin();
            if (theKing.FlipSprite)
            {
                spriteBatch.Draw(theKing.Sprite, theKing.CalculatePosition, null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.FlipHorizontally, 0);
            }
            else
            {
                spriteBatch.Draw(theKing.Sprite, theKing.Position, Color.White);
            }
            spriteBatch.End();
        }
    }
}

```

King.cs

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace TestGame1
{
    class King
    {

        private String spriteRef;
        private Texture2D sprite;
        private Vector2 position;
        private Vector2 speed;
        private Vector2 maxSpeed;
        private Boolean flipSprite;
        private Vector2 accel;

        public String SpriteReference
        {
            get { return spriteRef; }
            set { spriteRef = value; }
        }
        public Texture2D Sprite
        {
            get { return sprite; }
            set { sprite = value; }
        }
        public int SpriteWidth
        {
            get { return sprite.Width; }
        }
        public int SpriteHeight
        {
            get { return sprite.Height; }
        }

        public Vector2 Position
        {
            get { return position; }
            set { position = value; }
        }
        public float PositonHorizontal
        {
            get { return position.X; }
            set { position.X = value; }
        }
        public float PositionVertical
        {
            get { return position.Y; }
            set { position.Y = value; }
        }

        public Vector2 CalculatePosition
        {
            get
            {
                //Trace.WriteLine("Hor: " + SpeedHorizontal);
                //Trace.WriteLine("Ver: " + SpeedVertical);
                if (SpeedHorizontal != 0 || SpeedVertical != 0)
                {
                    if (SpeedHorizontal != 0)
                    {
                        if (SpeedHorizontal > 0 || SpeedHorizontal < 0)
                        {
                            position.X += SpeedHorizontal / 2;
                        }
                    }
                    if (SpeedVertical != 0)
                    {
                        if (SpeedVertical > 0 || SpeedVertical < 0)
                        {
                            position.Y += SpeedVertical / 2;
                        }
                    }
                }
                return Position;
            }
        }

        public Vector2 Speed
        {
            get { return speed; }
            set { speed = value; }
        }
        public float SpeedHorizontal
        {
            get { return speed.X; }
            set { speed.X = value; }
        }
        public float SpeedVertical
        {
            get { return speed.Y; }
            set { speed.Y = value; }
        }
        public Vector2 MaxSpeed
        {
            get { return maxSpeed; }
            set { maxSpeed = value; }
        }
        public float MaxSpeedHorizontal
        {
            get { return maxSpeed.X; }
            set { maxSpeed.X = value; }
        }
        public float MaxSpeedVertical
        {
            get { return maxSpeed.Y; }
            set { maxSpeed.Y = value; }
        }

        public Vector2 Acceleration
        {
            get { return accel; }
            set { accel = value; }
        }
        public float AccelerationHorizontal
        {
            get { return accel.X; }
            set { accel.X = value; }
        }
        public float AccelerationVertical
        {
            get { return accel.Y; }
            set { accel.Y = value; }
        }

        public Boolean FlipSprite
        {
            get { return flipSprite; }
            set { flipSprite = value; }
        }

        public King()
        {
            SpriteReference = "King";
            Position = new Vector2(10.0f, 100.0f);
            Speed = new Vector2(0.0f, 0.0f);
            Acceleration = new Vector2(0.01f, 0.02f);
            FlipSprite = true;
        }

        public void FlipSpriteHorizontal()
        {
            if (FlipSprite)
                FlipSprite = false;
            else
                FlipSprite = true;
        }

    }
}

```

# Answer
Base Game class already has GameComponentCollection in it and it handles calling updates and draws, so don't create new one and just use theirs.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.components

*By the way: I think the GameComponent is meant for more complex things then just game entities, for stuff like SceneGraphComponent (that would handle drawing of every SceneNode class) or NetworkingComponent (that would send and recieve queued packets)*
> 5 votes

# Answer
By looking at your code, you need to initialize ***components*** first.

```
components = new GameComponentCollection();

```
> 0 votes

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


# Question
Title: 2D Platformer - Methods to Implement a Whip Weapon
I hope posting here isn't a faux pax, if it is please feel free to direct me to the correct location. Or, if there is a thread that already covered this I would love to be pointed in its direction.

I've tried looking in quite a few different forums and I can't seem to find very much information about this. What I'm looking to do is implement a whip weapon for a character that's similar to that of Castlevania 4's whip.

I have no idea where to start. I'm really just looking for any information. Things like how to program it, the idea of how it was done in the game, really just anything to help me figure out how to make a whip like Castlevania 4.

I would appreciate any help. Thank you.

# Answer
I think most resources you find that have to deal with ropes will help you here. There is a lot of information about simulating ropes. For example:

2D Rope Collision Detection

Or

Lightning whip particle effects

Or

What are the maths behind 'Raiden 2' purple laser?

Since a whip is basically like a rope, I think these resources will help you. Good luck!
> 5 votes

# Answer
Often times you'll find that there doesn't exist information for exactly what it is you want to do on the internet.

But you can find tutorials for things that are close.

I imagine if you look for how to make platformers in Unity you'll get some useful results. Probably for metroidvania style games as well.

As for making a weapon with that particular behavior, that's going to be trickier. You'll need to decide what exactly happens when someone swings a whip like that, and determine how to represent it.

Programming in general is like this, but in video game programming especially you'll frequently come across vague, strange problems that are difficult to resolve. What you need to do is break things down define what it is you want to accomplish.

This is part of why I suggested looking at some tutorials. That will give you some context. While this might not even help you determine how to implement your desired feature? You'll have a better idea of how to ask for help.

If on the other hand you already did do all that and are just really uncertain of how to represent a whip that bounces all over the place? Frankly I don't blame you. That's a difficult problem.

There's a few ways I think you could go with this, so I'd say the first thing to do is settle on and visualize the specific way in which you want the whip to work.

Probably your answer is to use several hit boxes. Make an approximation of a flailing morning star.

Sorry if my answer is a bit long and rambling.
> 2 votes

# Answer
Having happened across your cross posting of this question on Reddit, it looks like you're just interested in determining the movement for the whip in "dangle" (and possibly also "flail" mode). The term you want to hunt for is Forward Kinematics (Complimentary links: Wikipedia, Some less complex math site).

Essentially, each section of the whip has a length and an rotation. For any link, `n`, after the first, its position is determined as being `n-1`'s length away in the direction of the `n-1`'s rotation. Start at the handle of the whip and determine locations of each section in turn down to the end of the whip.

Setting how much a link can rotate each tick is up to you and your desired physics outcome.
> 1 votes

# Answer
castlevania's is fairly simple, I would create a spritesheet of the whip extending and use an animation class to play it in game and simply extended the bounding rectangle by the size of the whip each frame and ensure that the handle is is the same position as the players hand
> 0 votes

---
Tags: unity
---


title: Geometry vs sprites

text:
# Question
Title: Geometry vs sprites
I'm developing an android game, where the enemies are geometrical shapes. Performance is a main goal for me so I was wondering if defining shapes directly in OpenGL would be more efficient than using sprites. Is it really faster or I'm missing something?

# Answer
I think it also depends on how many shapes you're going to draw and how complex they are. If these are simple rectangles/triangles, you should choose to directly draw the geometry (because you're going to be drawing 2 triangles for each sprite anyway).

An advantage of using sprites (textured quads) is that your "sprite" can be arbitrarily complex and also have anti-aliased edges without much cost (because the edges are in the texture). This approach could potentially use a lot of graphics-memory if all your shapes happen to be different.

When drawing the geometry directly in OpenGL you don't have to care all that much about how many different shapes you have. It also works much better than the texture approach if you plan to scale your entities a lot. But if you want anti-aliased edges, you'll have to enable anti-aliasing which in turn has an impact on performance.

This probably doesn't answer your question directly. But I think the type of shape (how complex, how many different types of shapes) and how you're planning to animate it (will they be scaled, change color?) directly influence the performance of each approach.
> 1 votes

# Answer
With meshes/geometry you can get better precision and look. Performance varies on shape complexity and size.

Every point/vertex is processed by vertex shader. Every face is rasterized to pixels. Every pixel is processed by fragment shader.

So if you are drawing rounded-corner rectangle then you would get better performance with sprite, because there is minimum of transparent pixels. If you are drawing shape like alphabet 'L' then you would probably get better performance with geometry, because of high amount of transparent pixels that are processed by fragment shader.
> 2 votes

---
Tags: android, sprites, opengl-es, performance, geometry
---


# Question
Title: Project updates don't show up on mobile device
I've made a small application with libgdx framework, which works perfectly on desktop. It runs on Android too, however once I change something in my main project and try to recompile it on my phone, it seems like the Android still runs the old version.

I've tried to re-install the app, but it does not help. The only way I can see the changes on my phone is to recreate a different Android project.

Any ideas what might be causing this kind of behavior?

My projects are created the way it is shown here: http://code.google.com/p/libgdx/wiki/ProjectSetup

EDIT: Not sure why, but everything seems to work fine after "re-installing" Eclipse

# Answer
> 1 votes
Maybe it's the fault of eclipse, not libgdx. Please check whether you tick Project-\>Build Automaticcally or not. Or else you can try to build by ant in command line. This is my complete compiling script:

```
cd "project_folder"
adb uninstall com.package
call ant clean
call ant debug
adb install "bin\project_debug.apk"
adb shell am start -n com.package/.MainActivity

```

# Answer
> 1 votes
I had similar problem, though I don't remember exact solution. It was one-time problem, which never appeared before and after and was also unexpected (I didn't do anything different from what I have done all the time). Try these steps:

* remove your app from Android device
* manually remove all directories containing bin data from every project associated with your game; rebuild all projects
* restart your IDE and Android device (I suppose this is most important for Android device)
* uncheck auto-build

You might also want to test it with other device, if available, to narrow possibilities.

---
Tags: android, libgdx
---


title: Freeglut vs SDL vs GLFW

text:
# Question
Title: Freeglut vs SDL vs GLFW
I need to port my game project from Android (written in C, OpenGL ES 2.0, thanks to NDK) to Windows and Linux platforms. Of course I will need to rewrite some platform dependent code, but for now I'm stuck with the question of which library to use for creating OpenGL context and handling input.

Just a quick googling gives me 3 candidates:

1. FreeGLUT - rewritten and free good old GLUT.
2. SDL - most well know one lib, used in many games.
3. GLFW - some kind of newer library, but simple and functional.

I'm quite new to PC development and don't see any significant differences between them. Can you help me with the choice? I need only core mouse/keyboard input and creation of OpenGL context. I'll be using GLEW to load OpenGL functions.

# Answer
> 41 votes
**GLFW** *is modern* and *has a very well defined scope*. It's also under very active development.

**SDL** on the other side *is rock solid* and has a lot features in different scopes but is somewhat lacking in all of them (for example: SDL can do audio, but you might prefer using OpenAL because its far superior in that matter). It might be notable that SDL was ported to many different platforms, unlike GLFW which is only for desktop platforms (win/linux/mac).

**GLUT**, well, *should be avoided*. There simply isn't really anything about it what makes it good.

---

In my opinion as perfectionist GLFW is the better choice. Because it does exactly what one wants, nothing less nothing more. The very active development is also a good sign for long term projects because it usually means that bugs will be fixed, that new features will be added, it will keep up with newer standards and that it won't be abadoned anytime near. This isn't important for a quick port or a 6-month game, but for a engine or a library you want to reuse I would keep that in mind.

---
Tags: opengl, windows, linux
---


# Question
Title: Revamping my GUI to be more efficient and less brute
I am building a Java game from scratch right now. So far, it runs fine, but the issue is with my GUI and how it works. Basically, it's a tile-based game. Each time the person moves a different image is displayed (basically I check to see what terrain they are on, and in what direction they moved then update that tile's Imageicon). I feel like it is a lot of brute force graphic work and I was wondering if anyone here could help me find a simpler method or class to preform the action. I use ImageIcons to basically make the game's GUI function right now. I was thinking about finding a way to have "layers", so I could have the terrain in the background and my person could just walk over it. Unless someone has a better idea.

Another long-term goal is to make the walk movement an animation. Right now, the person just pops over 1 tile, I want to implement some basic walking animation for that movement of tile to tile. I feel like that would be easier to do if I had a way make the person be a separate object compared to the terrain/map.

Any suggestions on how to do this would be very helpful! :)

IMAGE REQUEST: Here is an older and later dated image of one region. Basically, I have a tile (ImageIcon) for each possible instance of where the hero is, and which way he is facing. But as stated, I want to get rid of that because it requires soooo much. There has to be an easier way to overlap the person and allow animation to each tile.

# Answer
> 2 votes
OK, i hope you don't try to market your game with the current obvious copyright issues.

Aside from that if I understand your problem your hero sprite has a background of every combination of background. In response I will say all you need to do is render top to bottom of your view port and make sure the hero has a transparent background.

As for the UI you could also draw it onto the map in a separate layer above the map making it able to be slightly transparent and any other effects.

**EDIT**

Since your player is a single cell in size it would be easy to render your grid like you are doing then simply render the player afterwards with a transparent background to ensure that what the play is standing on is seen.

A more advanced way is to render in layers in such a way that your player can walk behind backs of buildings and trees.

To do this you will need to multiple passes of rendering for example one way could be

1. Render the ground information, in your current map you have grass and water etc.
2. Render the tiles that cant be passed through sprites such as bottom part of buildings and bottoms of trees and your bushes.
3. Render the player on top of all that.
4. Render the tops of buildings and tree, this will allow a player to be rendered behind the tops of objects.
5. Finally render your UI layer with buttons etc (these will be drawn and the click handled by you not java).

The advantage to doing 1 and 2 separately comes into play when you want different ground textures for example, rocky grass, desert. by having transparency on all objects backgrounds it will allow the background through for example your bushes could be rendered on desert or grass with no extra images.

Remember tho to render all of this to an off screen image and then display the image after completions as it will ensure your frame rate don't drop to the increase in rendering.

If I haven't understood your question please clarify and i will update my answer.

---
Tags: java, animation, gui, browser-based-games
---


title: Touch area double sized on newer device

text:
# Question
Title: Touch area double sized on newer device
I am developing a universal puzzle game, in which I have used separate image for iPhone4 and for iPhone3, iPhone4 image is double in size of iPhone3 image. My issue is for iPhone4, touch area of image for iPhone4 image is taking double size. Suppose I have an image size for iPhone4 of `20x40` and for iPhone3 of `10x20`, the touch area for iPhone4 image is `40x80`. I don't know how it's happening I worked out in my code but I didn't get any solution of this issue. Touching is working fine in iPhone3, touching within the sprite rectangle.

Can you help me to solve this issue? Or tell me what I am forgetting to code for iPhone4 touching so that it takes touch within sprite rectangle?

Below is my code: \`

```
    -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

    {
     UITouch *touch = [touches anyObject];
     touchLocation = [touch locationInView: [touch view]];
     touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
     touchLocation = [self convertTouchToNodeSpace:touch];
     NSLog(@"touch location x = %f , y =%f",touchLocation.x,touchLocation.y);
     CCSprite * sp= [CCSprite spriteWithFile:@"1.png"];
    sp.position = ccp(touchLocation.x ,touchLocation.y);
    // [self addChild:sp z:100];
    CGRect myrec = [invisible[0] boundingBox];

    if (CGRectContainsPoint(myrec, touchLocation) ) {
    NSLog(@"oneeeeeeee");
    }

     [self selectSpriteForTouch:touchLocation];
     // return TRUE;
   }

     - (void)panForTranslation:(CGPoint)translation
    {
     if (selSprite) {

    CGPoint newPos = ccpAdd(selSprite.position, translation);
    selSprite.position = newPos;

      }
   }

     - (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    Location = [touch locationInView: [touch view]];
     Location = [[CCDirector sharedDirector] convertToGL:Location];
    Location = [self convertTouchToNodeSpace:touch];
    NSLog(@"touch moved location x = %f , y =%f",Location.x,Location.y);

      //touchLocation = [self convertTouchToNodeSpace:touch];

   CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
   oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
   oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];
   CGPoint translation = ccpSub(Location, oldTouchLocation);

   if (CGRectContainsPoint(selspriterect,Location)) {
    [self panForTranslation:translation];
   }

     if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    {
    NSLog(@"respond to selector");

    CGFloat scale = [[UIScreen mainScreen] scale];

    if (scale > 1.0)
    {
        NSLog(@"iphone 4s");
        CGPoint mypoint = CGPointMake(80, 357);
        CGPoint mypoint1 = CGPointMake(237, 360);
        CGPoint mypoint2 = CGPointMake(79, 255);
        CGPoint mypoint3 = CGPointMake(237, 247);
        CGPoint mypoint4 = CGPointMake(78, 153);
        CGPoint mypoint5 = CGPointMake(239, 140);

        CCSprite *disablesprite=nil;
        switch (selSprite.tag) {
            case 0:
                if (CGRectContainsPoint( [dest[0] boundingBox] , mypoint ) ) {
                    NSLog(@"oneeeeee collided");
                    dest[0].position =  ccp(192,380);
                    // selSprite = disablesprite;
                }
                break;
            case 1:
                if (CGRectContainsPoint( [dest[1] boundingBox] , mypoint1 ) ) {
                    NSLog(@"two collided");
                    dest[1].position =  ccp(258,379);

                }
                break;
            case 2:
                if (CGRectContainsPoint( [dest[2] boundingBox] , mypoint2 ) ) {
                    NSLog(@"three collided");
                    dest[2].position =  ccp(173,281);
                }
                break;
            case 3:
                if (CGRectContainsPoint( [dest[3] boundingBox] , mypoint3 ) ) {
                    NSLog(@"four collided");
                    dest[3].position = ccp(258,281);

                }
                break;
            case 4:
                if (CGRectContainsPoint( [dest[4] boundingBox] , mypoint4 ) ) {
                    NSLog(@"five collided");
                    dest[4].position =   ccp(166,181);
                }
                break;
            case 5:
                if (CGRectContainsPoint( [dest[5] boundingBox] , mypoint5 ) ) {
                    NSLog(@"six collided");
                    dest[5].position =  ccp(258,176);

                }
                break;
            default:
                break;
        }

    }
    else {

    CGPoint mypoint = CGPointMake(106, 329);
    CGPoint mypoint1 = CGPointMake(208, 329);
    CGPoint mypoint2 = CGPointMake(97, 220);
    CGPoint mypoint3 = CGPointMake(217, 220);
    CGPoint mypoint4 = CGPointMake(92, 124);
    CGPoint mypoint5 = CGPointMake(212, 124);

    CCSprite *disablesprite=nil;
    switch (selSprite.tag) {
    case 0:
        if (CGRectContainsPoint( [dest[0] boundingBox] , mypoint ) ) {
            NSLog(@"oneeeeee collided");
            dest[0].position =  ccp(125,320);
            // selSprite = disablesprite;
        }
        break;
    case 1:
        if (CGRectContainsPoint( [dest[1] boundingBox] , mypoint1 ) ) {
            NSLog(@"two collided");
            dest[1].position =  ccp(200,312);

        }
        break;
    case 2:
        if (CGRectContainsPoint( [dest[2] boundingBox] , mypoint2 ) ) {
            NSLog(@"three collided");
            dest[2].position =  ccp(117,209);
        }
        break;
    case 3:
        if (CGRectContainsPoint( [dest[3] boundingBox] , mypoint3 ) ) {
            NSLog(@"four collided");
            dest[3].position =  ccp(200,208);

        }
        break;
    case 4:
        if (CGRectContainsPoint( [dest[4] boundingBox] , mypoint4 ) ) {
            NSLog(@"five collided");
            dest[4].position =  ccp(113,127);
        }
        break;
    case 5:
        if (CGRectContainsPoint( [dest[5] boundingBox] , mypoint5 ) ) {
            NSLog(@"six collided");
            dest[5].position =  ccp(207,126);

        }
        break;
    default:
        break;
  }
    }
      }

   }

    -(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
      CGPoint mypoint = CGPointMake(106, 329);
      CGPoint mypoint1 = CGPointMake(208, 329);
      CGPoint mypoint2 = CGPointMake(97, 220);
       CGPoint mypoint3 = CGPointMake(217, 220);
     CGPoint mypoint4 = CGPointMake(92, 124);
     CGPoint mypoint5 = CGPointMake(212, 124);
     switch (selSprite.tag) {
      case 0:
        if (CGRectContainsPoint( [dest[0] boundingBox] , mypoint ) ) {
            NSLog(@"oneeeeee collided");
            if (corsprite == TRUE) {
                correctplace++;
                corsprite = FALSE;
            }
        }else {
            selSprite.position = ccp(110,50);
        }
        break;
    case 1:
        if (CGRectContainsPoint( [dest[1] boundingBox] , mypoint1 ) ) {
            NSLog(@"two collided");
            if (corsprite2 == TRUE) {
                correctplace++;
                corsprite2 = FALSE;
            }
        }else {
            selSprite.position = ccp(110, 65);
        }
        break;
    case 2:
        if (CGRectContainsPoint( [dest[2] boundingBox] , mypoint2 ) ) {
            NSLog(@"three collided");
            if (corsprite3 == TRUE) {
                correctplace++;
                corsprite3 = FALSE;
            }
        }else {
            selSprite.position =ccp(130, 10);
        }
        break;
    case 3:
        if (CGRectContainsPoint( [dest[3] boundingBox] , mypoint3 ) ) {
            NSLog(@"four collided");
            if (corsprite4 == TRUE) {
                correctplace++;
                corsprite4 = FALSE;
            }
        }else {
            selSprite.position = ccp(215, 10);
        }
        break;
    case 4:
        if (CGRectContainsPoint( [dest[4] boundingBox] , mypoint4 ) ) {
            NSLog(@"five collided");
            if (corsprite5 == TRUE) {
                correctplace++;
                corsprite5 = FALSE;
            }
        }else {
            selSprite.position = ccp(220,70);
        }
        break;
    case 5:
        if (CGRectContainsPoint( [dest[5] boundingBox] , mypoint5 ) ) {
            NSLog(@"six collided");
            if (corsprite6 == TRUE) {
                correctplace++;
                corsprite6 = FALSE;
            }
        }else {
            selSprite.position = ccp(220,70);
        }
        break;
    default:
        break;
   }

```

\`

# Answer
> 5 votes
On iOS there are two different units of measurement. *Points* and *Pixels*. On older devices a point is equal to a pixel. On new devices, there are two pixels for each point, both vertically and horizontally (so totally 4 pixels per point). An iPhone 3 has `480x320` pixels and `480x320` points. Whereas an iPhone 4 has `960x640` pixels and `480x320` points! The important bit here is that the number of points remain the same for old and new devices.

So I'm assuming you're working with pixel sizes instead of point sizes here. When you define a rectangle to be `20x40` on a new device, then this is in points, **not** pixels. Which in turn results in a `40x80` pixel rectangle, which is of course double the size of your image. Your image of size `20x40` is actually `10x20` points in size (on an iPhone 4).

I don't know how you retrieve your rectangle sizes. If they are hard-coded, just always use the one for the low-res device. If you're measuring them at runtime, always use methods like `contentSize` instead of `contentSizeInPixels`.

**Summary**: Work with points instead of pixels, as points remain the same across iPhone 1 - 4.

---
Tags: cocos2d-iphone, ios, objective-c
---


# Question
Title: Extracting tiles from a tileset programatically?
How do I programatically extract tiles from a tileset such as this one: http://opengameart.org/sites/default/files/grassland\_tiles.png

I want to use these tiles in my game. I see that some tiles here are of different sizes (or maybe all tiles are a multiple of some fixed size). For example, if I want to use one of the tree tiles in my program, how can I figure out what offset into the tileset image I must use, and how big of a sub-image i must extract? I don't see any metadata associated with any of these tilesets that I can use.

Thanks!

# Answer
You generally need some text file or other metadata to describe the contents of a texture atlas like this.

I suspect you went here: http://opengameart.org/content/grassland-tileset to get this URL? (That would've been handy in your OP.)

If so, you must've missed this note:

> To use the tile set in Tiled v0.8, get the necessary files from the Flare git repo.

The git repo is: https://github.com/clintbellanger/flare/tree/master/tiled/grassland

Its got one `.txt` several `.tmx` files. The `.tmx` files seem to describe the location of specific items in the atlases.
> 3 votes

---
Tags: tiles, tilemap
---


# Question
Title: Any social gaming services for JavaScript games?
I'm currently planning on building a HTML5/JavaScript game for the various platforms (Browser, iOS, Android, and WinMo7). I, obviously, would like there to be simple multiplayer (1v1, asynch), leaderboards, etc.

Finding a service that provides this for native applications is easy (Scoreloop, Gree, etc.) but I have yet to find one that allows access through JavaScript. So with that said, does such a service/platform exist or am I looking at creating my own (probably with node)?

# Answer
> 3 votes
Try Facebook. You have to host your game and everything, they just provide the actual playerbase and the social aspect, which are quite valuable. I believe that you still have to code up the leaderboards and all that, and I suggest Node.js + SQLite, it's a nice and robust solution for a simple project.

As for the achievement system, I'm not sure. I am not aware of any currently available HTML5 game engine that can handle these, as they (the achievements) can get quite game specific.

But, thankfully, they're not hard to implement, let me explain how I would do it...

A game can be considered a stream of events. Events, as in "player killed x", and "player gained new level", or "x killed y", you get the point. What you will need to do, to effectively implement achievements, is make an **event system** for your game.

To realize why, I must first explain what these are, although you probably already know all this because you're using HTML. Others might not, so I'll do it anyway.

An event system is consisted of **events** and **listeners**. You can implement listeners as functions that subscribe to certain events: each time an event fires, that function is executed, passing the objects and some other data to it as an argument.

I suggest that you have an EventManager that gets called on each game loop iteration (or less frequently), and holds all the listeners and other information.

If you want to listen to a certain event, you simply do this: `eventManager.register("kill", function(killer, victim){...})`.

This is, for example, how you would implement an achievement that requires the player to kill 100 enemies (it's a pretty bad achievement in terms of game design, but it's simple to implement).

```
var killed = function(killer, victim)
{
    if (!(killer instanceof Player)) //Only players can get this achievement.
    {
        return false;
    }

    ++ killer.n; //This is a Player object, usually, and it keeps track of how many times it has performed this action.

    if (killer.n == 100)
    {
        killer.achievement("100done"); //The player should know how to handle this, no need to hardcode it.
    }
}

eventManager.register("kill", killed);

//Later on, when the kill actually happens:

if (enemy.health <= 0)
{
    eventManager.fire("kill", [player, enemy]); //Implement this however you wish.
}

```

You could, of course, hardcode all of this in the actual game logic, but that would be awful and would get really messy. Also, you've built yourself a nice event system that you could use for many other situations too!

# Answer
> 1 votes
I was able to find a social gaming service for JavaScript that offers most of what I'm looking for (everything but the actual multiplayer servers to use). It's called clay.io and can be found at http://clay.io/ :)

---
Tags: javascript, multiplayer, html5, leaderboards
---


title: Rotating a polygon around it's center

text:
# Question
Title: Rotating a polygon around it's center
I have drawn a ship using three lines, and would like to rotate the ship around its axis in opengl, I have tried the following, but the ship translates while rotation!.

```
void Ship::Draw( )
{
    gl::pushMatrices();
    gl::translate(Vec2f(-m_Pos.x, -m_Pos.y));
    gl::rotate(m_Angle);
    gl::translate(Vec2f(m_Pos.x,m_Pos.y));
    gl::color(ci::Color(1,0,0));
    gl::drawLine(Vec2f(281,70),Vec2f(383,123));
    gl::drawLine(Vec2f(310,85),Vec2f(310,160));
    gl::drawLine(Vec2f(383,123),Vec2f(281,176));

    gl::popMatrices();
    m_Angle+=0.2f;
}

```

# Answer
> 2 votes
To rotate a polygon around its centre like this, you need to draw it around the origin.

Currently you're drawing it off-centre:

```
gl::drawLine(Vec2f(281,70),Vec2f(383,123));
gl::drawLine(Vec2f(310,85),Vec2f(310,160));
gl::drawLine(Vec2f(383,123),Vec2f(281,176));

```

What this means is that these points are rotated around (0,0) by your angle `m_Angle`.

Instead, put equal amounts on either side of (0,0):

```
gl::drawLine(Vec2f(-43,-52),Vec2f(59,1));
gl::drawLine(Vec2f(-14,-31),Vec2f(-14,38));
gl::drawLine(Vec2f(59,1),Vec2f(-43,54));

```

# Answer
> 1 votes
Have you done any other `gl::translate` before that? What is the state of the `GL_MODELVIEW` matrix at that time? Take into account that if you have accommulated other transformations then `gl::translate(-m_pos.x, -m_pos.y)` does not bring you back to the origin. I would call `glLoadIdentity()` rather then `gl::translate(-m_pos.x, -m_pos.y)`, then you rotate and translate where you want to go.

---
Tags: c++, opengl, mathematics
---


title: Tilting a platform on its axis?

text:
# Question
Title: Tilting a platform on its axis?
I'm wondering how I can tilt a platform on it's center/axis.

For example, if the player steps on the left of the center, it should tilt to that side like in this picture.

Can a platform like this still be an array of tiles? or does it have to be solid. Are there any good libraries (javascript) to handle this kind of transformation and the calculations required?

Could someone provide example code for what this might look like? Thank you.

# Answer
I'm assuming here you're using `<canvas>`:

You can use the `rotate` function on the context to rotate any drawing functions. Draw the tiles with offsets around the centre, then post-translate them. Confusingly you write the translation first and it gets applied second, but here's how you'd do it:

```
var ctx = document.getElementById('your_canvas').getContext('2d');

ctx.translate(platorm_centre.x, platform_centre.y);
ctx.rotate(platform_angle);

ctx.drawImage( platform_image,
               -platform_width/2, -platform_height/2,
               platform_width, platform_height );

// Afterwards, go back to an identity transform:
ctx.setTransform( 1, 0, 0, 1, 0, 0 );

```

You can replace the single draw call with multiple draw calls to tiles if you subtract the platform's centre from the tile's world position.

Important to note is none of this applies to your physics to actually stand on the platform and make it tilt. I'm assuming you've already solved that problem. :)
> 1 votes

---
Tags: javascript, html5, platformer
---


# Question
Title: Multilingual data bases for most common words and phrases used in games
Games tend to have easy to understand instructions/menus/tutorials and so on, so I was wondering whether...

Are there multilingual data bases, built-in with the most common phrases used in games?

For instance Start, Resume, Play, Pause, Edit Profile, Awards, etc.

Any info is appreciated.

# Answer
> 2 votes
Its not game specific, but see: https://stackoverflow.com/questions/1792353/database-of-common-translated-phrases-for-localization

Basically the answers there boil down to:

All that said, I suspect there are some 'gamey' translations of some phrases that warrant a game-specific resource. Hopefully someone else has those details.

---
Tags: databases
---


# Question
Title: Why is it a bad idea to store methods in Entities and Components? (Along with some other Entity System questions.)
*This is a followup to this question, which I answered, but this one tackles with a much more specific subject.*

## This answer helped me understand Entity Systems even better than the article.

I've read the (yes, the) article about Entity Systems, and it told me the following:

**Entities** are just an id and an array of components (the articles says that storing entities in components isn't a good way of doing things, but doesn't provide an alternative).
**Components** are pieces of data, that indicate what can be done with a certain entity.
**Systems** are the "methods", they perform manipulation of data on entities.

This seems really practical in many situations, but the part about components being just data classes is bothering me. For example, how could I implement my Vector2D class (Position) in an Entity System?

The Vector2D class holds data: x and y coordinates, but it also has *methods*, which are crucial to its usefulness and distinguish the class from just a two element array. Example methods are: `add()`, `rotate(point, r, angle)`, `substract()`, `normalize()`, and all other standard, useful, and absolutely needed methods that positions (which are instances of the Vector2D class) should have.

If the component was just a data holder, it wouldn't be able to have these methods!

One solution that could probably pop up would be to implement them inside systems, but that seems very counter-intuitive. These methods are things that I want to perform **now**, have them be complete and ready to use. I don't want to wait for the `MovementSystem` to read some expensive set of messages that instruct it to perform a calculation on the position of an entity!

And, the article very clearly states that **only** systems should have *any* functionality, and the only explanation for that, which I could find, was "to avoid OOP". First of all, I don't understand why should I refrain from using methods in entities and components. The memory overhead is practically the same, and when coupled with systems these should be very easy to implement and combine in interesting ways. The systems, for example, could only provide basic logic to entities/components, which know the implementation themselves. If you ask me - this is basically taking the goodies from both ES and OOP, something that can't be done according to the author of the article, but to me seems like a good practice.

Think about it this way; there are many different types of drawable objects in a game. Plain old images, animations (`update()`, `getCurrentFrame()`, etc), combinations of these primitive types, and all of them could simply provide a `draw()` method to the render system, which then doesn't need to care about how the sprite of an entity is implemented, only about the interface (draw) and the position. And then, I would only need an animation system which would call animation-specific methods that have nothing to do with the rendering.

And just one other thing... Is there really an alternative to arrays when it comes to storing components? I see no other place for components to be stored other than arrays inside an Entity class...

Maybe, this is a better approach: store components as simple properties of entities. For example, a position component would be glued to `entity.position`.

The *only* other way would be to have some kind of a strange lookup table *inside* systems, that references different entities. But that seems **very** inefficient and more complicated to develop than simply storing components in the entity.

# Answer
> 27 votes
I think it's totally fine to have simple methods for accessing, updating or manipulating the data in components. I think the functionality that should stay out of components is logical functionality. Utility functions are just fine. Remember, the entity-component system is just a guideline, not strict rules you need to follow. Don't go out of your way to follow them. If you think it makes more sense to do it one way, then do it that way :)

**EDIT**

To clarify, you're goal is not to avoid OOP. That would be pretty difficult in most of the common languages used these days. You're trying to minimize inheritance, which is a large aspect of OOP, but not required. You want to get rid of the Object-\>MobileObject-\>Creature-\>Bipedal-\>Human type inheritance.

However, it's OK to have some inheritance! You're dealing with a language that's heavily influenced by inheritance, it's very difficult to not use any of it. For example, you can have a `Component` class or interface that all your other components extend or implement. Same deal with your `System` class. This makes things a lot easier. I strongly recommend you take a look at the Artemis framework. It's open source and it has some example projects. Open those things up and see how it works.

For Artemis, entities are stored in an array, simple. However, their components are stored in an array or arrays (separate from the entities). The top level array groups the lower level array by component type. So each component type has its own array. The lower level array is indexed by entity ID. (Now I'm not sure if I'd do it that way, but that's the way it's done here). Artemis reuses entity IDs, so the max entity ID doesn't get larger than your current number of entities, but you can still have sparse arrays if the component is not a frequently used component. Anyway, I won't pick that apart too much. This method for storing entities and their components seems to work. I think it would make a great first pass at implementing your own system.

The entities and components are stored in an separate manager.

The strategy you mention, making entities store their own components (`entity.position`), is kind of against the entity component theme, but it's totally acceptable if you feel that makes the most sense.

# Answer
> 10 votes
'That' article is not one I particularly agree with, so my answer will be somewhat critical I think.

> This seems really practical in many situations, but the part about components being just data classes is bothering me. For example, how could I implement my Vector2D class (Position) in an Entity System?

The idea isn't to ensure that nothing in your program is anything other than an entity ID, component, or system - it's to ensure that entity data and behaviour is created through composing objects rather than either using a complex inheritance tree or worse trying to put all possible functionality into one object. To implement these components and systems you will certainly have normal data like vectors which are, in most languages, best represented as a class.

Ignore the bit in the article that suggests this is not OOP - it is just as OOP as any other approach. When most compilers or language runtimes implement object methods, it is basically just like any other function, except there is a hidden argument called `this` or `self`, which is a pointer to a place in memory where that object's data is stored. In a component based system, the entity ID can be used to find where the relevant components (and thus data) are for a given entity. Thus the entity ID is equivalent to a this/self pointer, and the concepts are basically the same thing, just rearranged a little.

> And, the article very clearly states that only systems should have any functionality, and the only explanation for that, which I could find, was "to avoid OOP". First of all, I don't understand why should I refrain from using methods in entities and components.

Good. Methods are an effective way of organising your code. The important thing to take away from the "avoid OOP" idea is to avoid using inheritance everywhere to extend functionality. Instead, break the functionality up into components that can be combined to do the same thing.

> Think about it this way; there are many different types of drawable objects in a game. Plain old images, animations (update(), getCurrentFrame(), etc), combinations of these primitive types, and all of them could simply provide a draw() method to the render system \[...\]

The idea of a component based system is that you wouldn't have separate classes for these, but would have a single Object/Entity class, and the image would be an Object/Entity that has an ImageRenderer, the Animations would be an Object/Entity that has an AnimationRenderer, etc. The relevant systems would know how to render these components and so there wouldn't need to be any base class with a Draw() method.

> \[...\] which then doesn't need to care about how the sprite of an entity is implemented, only about the interface (draw) and the position. And then, I would only need an animation system which would call animation-specific methods that have nothing to do with the rendering.

Sure, but this doesn't work well with components. You have 3 choices:

* Every component implements this interface and has a Draw() method, even if nothing gets drawn. If you did this for every bit of functionality then components would look pretty ugly.
* Only components that have something to draw implement the interface - but who decides which components to call Draw() on? Does a system have to somehow query each component to see what interface is supported? That would be error-prone and potentially tricky to implement in some languages.
* Components are only ever handled by their owning system (which is the idea in the linked article). In which case, the interface is irrelevant because a system knows exactly what class or object type it's working with.

> And just one other thing... Is there really an alternative to arrays when it comes to storing components? I see no other place for components to be stored other than arrays inside an Entity class...

You can store the components in the system. The array isn't the issue, but where you store the component is.

# Answer
> 2 votes
A vector is data. The functions are more like utility functions - they're not specific to that instance of the data, they can be applied to all vectors independently. A nice way of thinking about it is: Can these functions be rewritten as static methods? If so, it's just utility.

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


# Question
Title: Easy way to do gravity in a simple game?
I'm looking for an easy, beginner friendly way to do gravity in a platformer. I've looked into Box2D tutorials, but they all seem very complicated.

All I want is a class that takes into account if my player is grounded, or airborn, and a nice little curve as he jumps. I know this shouldn't be more than a few lines of code, and learning a library seems excessive.

Anyone mind helping me out?

# Answer
So, implementing gravity has some prerequisites. A big one is a time keeping system. One good read for time systems is Fix Your Timestep! by gafferongames.com. The time system ties in tightly to the update loop. See deWITTERS Gameloop for info on implementing an update loop (which covers time step too). Once you have an update loop with a delta time for each iteration, you're pretty much ready.

So, you main game will have something like:

```
update() {
    deltaTime = getCurrentTime() - runningTime; //deltaTime is called "frameTime" too
    runningTime = getCurrentTime();

    mainCharacter.update(deltaTime);
}

```

and inside that main character update method it'll be like:

```
update(float deltaTimeInMS) {

    if (onSolidGround())
        gravity = 0;
    else
        gravity = GLOBAL_GRAVITY; //note that global gravity is negative

    velocity.y += gravity * deltaTimeInMS;
}

```

Now this is a pretty basic way of doing it, and it'll be passable for simple games. I wouldn't recommend it for larger scale games however.
> 4 votes

---
Tags: javascript, html5, html-canvas
---


title: Unable to generate standalone noise

text:
# Question
Title: Unable to generate standalone noise
I've been stuck this evening on getting a Perlin Noise function to generate by itself. Every time I run the program without adding to different types of noise together it calls an ArgumentException error.

Here is my code I'm using.

```
        //perlin gen
        Random rand = new Random();
        double freq = 1 / 32.0;
        double lacu = 3.0;
        int octave = 5;
        double pers = 0.5;
        int seed = 1;

        Perlin perlin = new Perlin(freq, lacu, pers, octave, seed, QualityMode.High);

        //init the noise map
        noiseMap = new Noise2D(128, 128);
        noiseMap.GeneratePlanar(1, 2, 1, 2, true);

```

And the error that it calls is here.

```
public void GeneratePlanar(double left, double right, double top, double bottom, bool seamless)
    {
        if (right <= left || bottom <= top || this.m_generator == null)
        {
            throw new ArgumentException();
        }

```

I've checked and re-checked the code multiple times, so I'm not sure what is going on that is making the GeneratePlanar function call the ArgumentException error.

# Answer
Place a breakpoint on `throw new ArgumentException();`. When it breaks check the values of `right`, `left`, `bottom`, `top` and `m_generator`. See which one is the problem. Is `m_generator` `null`? Does `right == left`? When the debugger breaks, you can see the call stack. The call stack will show you all the function calls that have lead to this function being called.

The debugger is just about the programmers best friend. The sooner you learn to use it the better. See this post I wrote for more details about debuggers.

I'm assuming that `this.m_generator` is null, since I see from your code that the other values are correct. Look in the code an see where `m_generator` gets set, then you'll know what you need to do to set it properly.
> 1 votes

# Answer
Where is m\_generator coming from? I don't see it listed in the rest of your code provided, so is it initialized somewhere else?

You could also put some debug prints just before throwing the exception, and seeing what the values you have for those variables are. Getting an idea why you're in there would be a start to fixing it.
> 1 votes

---
Tags: xna, c#, perlin-noise
---


# Question
Title: Instancing pixel shader parameters -- pass instance data through vertex shader?
I'm working on a deferred shader, and I want to use instancing to draw point lights.

From what I understand, I can send the instance data through the vertex shader and pass it through unchanged to the pixel shader. Is this the correct way to do it, or can I send the instance data straight to the pixel shader somehow?

# Answer
> 1 votes
> can I send the instance data straight to the pixel shader somehow?

What would that mean, exactly? The values your fragment (or pixel if you insist) shader gets are per-vertex values interpolated across the face of the primitive, and constant uniform values that do not change within a draw call.

There is no way to magic a vertex stage input into a vertex stage output. There must be a vertex shader and it must write that input into the output.

> I want to use instancing to draw point lights.

You probably do not. Instancing usually isn't a performance win unless you're talking about thousands of instances. If you only have 20 point lights, it's not going to be worthwhile.

At the very least, you should profile it before committing to it.

---
Tags: fragment-shader, instancing, deferred-shading
---


# Question
Title: Running both the server and the client within the same process
**Question**

I have just started working with Lidgren and networking for the first time, and I've come to the realisation that it is possible to run both the server and the client within the *same* process.

*Is this practice discouraged for any reason?*

**Context**

The reason I'm asking is because I theorized that this concept might allow me to treat both singleplayer and multiplayer modes as one and the same, which would be very helpful.

Following my line of thought, this is the distribution I had in mind:

* Singleplayer - 1 server + 1 client in the same process. How fast are the communications?
* Multiplayer - Same as singleplayer for the host + 1 aditional client for each *other* player.

The execution flow I'm picturing is for clients to recieve user input and send a notification to the server. Then the server validates it, and broadcasts an action to be executed by all the clients. It shouldn't matter if there is only one client (i.e. singleplayer) or multiple clients (i.e. multiplayer).

# Answer
This is basically a process versus thread question, both aren't too different, sometimes threads are called lightweight processes. The biggest difference is that a separate process has it's own address space but there are other differences (1):

**Per process**

* address space
* Global variables
* Open files
* Child processes
* Pending alarms, interrupts and signal handlers

**Per thread**

* Program counter
* Registers
* Stack
* State

Based on these differences it could be handy to have a server and client thread in the same process so that you can share file handles and global variables. This would be an argument for the 'in the same process' approach, another (small) argument would be that you only get one 'Windows Firewall' pop-up per process. An argument for the 'different process' approach would be that a person can run multiple servers without having to run multiple clients. This would be ideal for a dedicated host like set-up and is an approach we commonly see in first person shooters.

Now as for the idea to have a server process or thread even for off-line play (and maybe even for single-player) this is a great idea that is used a lot in practice. You can tell a lot of games do this by looking at the loading screen, small hints like 'receiving' will give it away. It's logical to do this since if you're going to make a multi-player most of the game rules will be governed by the server, so why not have it govern them for single-player? This reduces the code you have to write and gives a clearer separation between client and 'game' which will improve your code quality.

Now how about communicating between processes and threads? Cross process communication can be done in a lot of ways, (named-)pipes, shared memory, COM, it really depends on the technology you're using. However if you're making a server you'll probably want to go with a a networking variant using sockets and something of the likes of TCP, this is of course where LIDGREN will come in handy.

A lot of these techniques are also valid for cross thread communication. But this depends even more on the techniques you're using. You could again go with TCP, but maybe an even simpler system would be events and some marshalling, although this could make your game loop non deterministic (2).

*Sources*

1. Operating systems design and implementation (the MINIX book), 3rd edition by Andrew S. Tanenbaum
2. Fix your timestep by Glenn Fiedler: http://gafferongames.com/game-physics/fix-your-timestep/
> 8 votes

---
Tags: networking
---


title: Tilemaps in a Entity System Framework?

text:
# Question
Title: Tilemaps in a Entity System Framework?
I have been reading up on Entity System Frameworks specifically Artemis. I am trying to decide if it is right for me. I strictly work on tile based 2d pixel art games, and I don’t think they will ever be that resource intensive. I have always used standard OOP with a lot of inheritance in the past.

My understanding of the Entity System Framework right now (I am not sure if I grasp it completely yet) is:

* Entities are nothing but ID's
* Components are nothing but dumb data added to an entities component pool
* Systems are update functions that are attached to the world to handle every entity that matches the Systems component signature

If my understanding is correct then I am having quite a bit of trouble conceptualizing adding tilemaps and AI Behavioral Trees into this framework. I will ask about AI in the future.

Should a tilemap be built into this framework? Or should it be kept separate to make it easy to generate with a tilemap editor?

If the tilemap should be built into this framework, is each tile a different entity? And the tilemap a system? Or is the tilemap itself a single entity with inheritance built off of it?

If the tilemap is sperate, what would be the best way of collision detecting entities against the external tilemap?

I understand that multiple options that I have listed might be correct, but if anybody has done this in the past they might be able to shed some light on my confusion. Maybe there is another alternative that I have not thought of?

Thank you.

# Answer
I implemented an entity component framework (similar to Artemis) after I'd already been in development for a while, but I don't think I would have done things differently if starting from a blank slate.

I have my world totally separate from the entity framework. It just didn't make sense to me to convert the world into some sort of entity or collection of entities. My world is 3D with cubes, but I believe the same applies for tiles. Entities make up everything else in the world, but the terrain is separate. However, when cubes are removed, they do spawn "material" entities.

Collision detection isn't too hard to tie in. Your world would likely have `isSolidAt(x,y)` type methods that your collision system will utilize. Honesty, I've said this once already today in a different answer, do whatever makes the most sense to you. You're not breaking any rules by making the tile map separate or making it an entity. Whatever you can wrap your head around is what's best. For me, that was keeping the world separate and making everything else entities.
> 9 votes

# Answer
I added tilemap as a separate component to entity (with all tiles inside) and there is also separate renderer for tile map, so I can render it in 3d or in 2d. To create all tiles as entities is possible but to expensive.

something like that:

```

Entity e("map");
e.addComponent(new Tilemap("1.xml"));
e.addComponent(new TilemapRenderer2d(graphics));

tile map is something like that
class Tilemap
{
  array of tiles;
  getTileAtPosition();
  isWalkable ; etc;
}

class ITilemapRenderer
{}

class TilemapRenderer2d
{
draw()
{
  foreach (tile in owner()->component()->tiles())
  {
    if (tile == ground) ground_sprite->draw() ....
  }
}

```

benefit in separating drawing from logic is base idea of MVC pattern
> 4 votes

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


title: Implementing Circular Sprite Masks

text:
# Question
Title: Implementing Circular Sprite Masks
So I've been scouring the interwebs for a couple of days with regards to how to implement sprite masking in XNA 4 and C#. Coming from a pet project I did in Flash, this was pretty easy as masks are part of the AS3 library, so implementing one was as simple as giving it a shape, size, and moving the X and Y co-ordinates of the mask to follow my character sprite.

Now I'm looking to do something similar in XNA. Think the Flash move in Pokemon lighting up caves, or, a better contextual example, the torch light effect in Terraria (alas, I can't find suitable pictures, but hopefully the gist is there).

So, essentially, I want to surround my sprite character with a circle - anything within that circle on the map is visible, and everything outside the circle is black.

The ways I've seen people similarly implement masks is via the StencilBuffer, Pixel Shading and via sprite overlay (You have a sprite of your "viewable area", you draw that on top of your player sprite and fill the rest of the viewport with black). Considering the latter two don't really have many directly applicable example projects that I can learn from on the internet (The one applicable StencilBuffer example I found is for WP7 dev, and no Pixel Shader stuff directly solves my problem), I've been leaning more towards the third idea of having a "viewpoint restriction" sprite that you place on top of the character sprite, then fill the rest of the map with black.

Is it possible to do this? And if so, could someone please help and link me to something relevant/give me some sample code/pseudo-code to work from. Again, I don't know if even this is the most effective way or if it's just easier to implement a proper mask with a Pixel Shader or StencilBuffer, but I have no idea how to go about that.

What do you guys think the best solution here would be?

# Answer
> 1 votes
Well, a pixel perfect way would be to use a stencil buffer where you you make the shape you want in advance and set that as the stencil then draw. But a crude method would be to use distance checks and don't draw anything outside that region and then just draw a black frame with a cutout around what you want (sort of like a stencil buffer)

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


title: Change the title name of a XNA window?

text:
# Question
Title: Change the title name of a XNA window?
I have tried to change the title with this source:

http://msdn.microsoft.com/en-us/library/ff966436.aspx

but this isn't working!? Help preciated!

# Answer
> 7 votes
`Window.Title = "My new title"`

Riemers

---
Tags: xna
---


title: HTML5 Canvas Depth Sorting

text:
# Question
Title: HTML5 Canvas Depth Sorting
I'm have problem with Isometric. I'm don't know how to name this "problem", but I'm show you some sceen what I get and what I'm need to get.

My code now drawing something like: http://2.bp.blogspot.com/\_rqhF\_8E1nlA/R59d\_PmoREI/AAAAAAAAAGo/3yHpmy55moc/s400/lore2.png

But I'm need draw something like this: http://3.bp.blogspot.com/\_rqhF\_8E1nlA/R59epfmoRFI/AAAAAAAAAGw/cE\_o-A0bvm0/s400/lore3.png

I'm hear this is "Depth sort" But what it is? how I'm can apply to my code and where I'm can learn this?

My code: 'http://jsdo.it/keichioor/exU1

# Answer
What you call "Depth sort" is sorting the elements to make the nearest of the camera drawing "at the end", in order to "cover" the others.

With your code it gives something like that http://jsfiddle.net/dievardump/FjrB9/3/ I Just added this function to sort the block Array :

```
var sortMap = function (a, b) {
    if (a.x > b.x){
        return 1;
    } else if (a.x < b.x) {
        return -1;
    } else {
        if (a.y > b.y) {
            return 1;
        } else {
            return -1;
        }
    }
}

```

because with your implementation, the more the x and the y are high, the more the element is near the camera.

Note : This implementation works for your current code, BUT for game/implementation with a moving camera, it exists generic function which gives you the distance to the camera, according to x/y (and sometimes z).
> 2 votes

---
Tags: javascript, html5, isometric, html-canvas
---


title: Character rotating around target

text:
# Question
Title: Character rotating around target
I'm using xaitment plugin for Unity as the AI for a demo level but I have a problem. My character is supposed to walk to random points but while it's walking there it's rotating around the point. I can't see what is causing this in my code, I'm assuming it's something to do with my `lookat` function

```
using UnityEngine;
using System.Collections;

public class MovementGoto : MonoBehaviour {

    // target position for the movement
    private Vector3 mTargetPosition;
    public Vector3 TargetPosition
    {
        get { return mTargetPosition;}
        set { mTargetPosition = value;}
    }

    public float Speed = 40.0f;

    // Update is called once per frame
    void FixedUpdate()
    {
        // get the current steering direction to reach the target position
        Vector3 walk = this.mTargetPosition - this.transform.position;

        // ignore 3d
        walk.y = 0.0f;
        walk.Normalize();

        // move into the desired direction
        this.transform.LookAt(this.TargetPosition);
        this.transform.Translate(walk);
    }
}

```

# Answer
> 1 votes
I think you may be using the `lookAt` function incorrectly if you're getting arcs from it. You're using steering, so you may need to overcome any initial velocity. Check out the red3d.com article on steering, particularly arrival.

From the article, arrival should look like:

```
target_offset = target - position
distance = length (target_offset)
ramped_speed = max_speed * (distance / slowing_distance)
clipped_speed = minimum (ramped_speed, max_speed)
desired_velocity = (clipped_speed / distance) * target_offset
steering = desired_velocity - velocity

```

---
Tags: unity, rotation
---


title: Angle between two points

text:
# Question
Title: Angle between two points
I have a character who walks to random points in my room in Unity. The problem is he always faces one direction, I want to write in C# a piece of code that will get the direction the character is currently facing and the position of the target, then works out the angle between them to turn the character that amount. I have tried the `LookAt` function but that makes the character walk in an arc shape towards the target which looks very unnatural as it constantly looks at the target.

# Answer
The LookAt function does this for you. You may be using it improperly, or something is wrong with your steering if you're having problems with this. You can try it this way too:

```
//find the vector pointing from our position to the target
dir = (Target.position - transform.position).normalized;

//create the rotation to look at the target
rotation = Quaternion.LookRotation(dir);

```

Now you can either snap towards that rotation, or you can do it slowly over time. (slowly over time means all this code needs to go into the update function)

```
//rotate over time
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * RotationSpeed);

//snap rotation
transform.rotation = rotation;

```

For 2D another alternate method would be Atan2:

```
angleBetween = Mathf.Atan2(point2Y - point1Y, point2X - point1X) * 180 / Math.PI))

```
> 12 votes

---
Tags: unity, rotation
---


title: Isometric Tile maps in Cocos2d-x

text:
# Question
Title: Isometric Tile maps in Cocos2d-x
Is there an specific isometric tile map handler in cocos2d-x? I can't find any.

# Answer
You can use CCTMXTiledMap: http://www.cocos2d-x.org/reference/native-cpp/da/d68/classcocos2d\_1\_1\_c\_c\_t\_m\_x\_tiled\_map.html

It supports isometric, hexagonal and orthogonal tiles.
> 5 votes

---
Tags: android, ios, isometric, tilemap, cocos2d-x
---


# Question
Title: Problem with monogame reference in monodevelop MAC
I've downloaded monogame, monotouch (test version) and monodevelop for MAC and I created a monotouch IOS project, I included the Lidgren and Monogame csproject inside my monodevelop project and I added the monogame reference in my project. But when I try to build it, my Main class doesn't find the Game class and Game.run();

My Main is the same code that I got monogame site:

```
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Microsoft.Xna;
using Microsoft.Xna.Samples;
using Microsoft.Xna.Samples.Draw2D;

namespace Microsoft.Xna.Samples.Draw2D
{
    [Register ("AppDelegate")]
    class Program : UIApplicationDelegate
    {
        private Game1 game; //doesn't find

        public override void FinishedLaunching (UIApplication app)
        {
            // Fun begins..
            game = new Game1();
            game.Run();
        }

        static void Main (string [] args)
        {
            UIApplication.Main (args,null,"AppDelegate");
        }
    }
}

```

and My appDelegate:

```
using System;
using System.Collections.Generic;
using System.Linq;

using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace testeios
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations
        UIWindow window;

        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            // create a new window instance based on the screen size
            window = new UIWindow (UIScreen.MainScreen.Bounds);

            // If you have defined a view, add it here:
            // window.AddSubview (navigationController.View);

            // make the window visible
            window.MakeKeyAndVisible ();

            return true;
        }
    }
}

```

I don't know what's happening, I follow every step to install it. has Someone the same problem?

# Answer
> 0 votes
Im not 100% sure but it looks like you are missing an include

```
using Microsoft.Xna.Framework;

```

Try that and see if it fixes your issue.

---
Tags: xna, c#, mono, monotouch, monogame
---


# Question
Title: Efficient physics and collision detection for RTS
I'm thinking about writing my own RTS game and while I'm more or less clear about how the game engine should work, I need some directions as to how to implement physics and collision detection.

Now, I am an experienced programmer but I have never ever done game dev before, so please excuse me my poor/incorrect terminology.

There will be a large 3D (i.e. planes, hills, valley, etc) world with lots of units, moving and/or fighting simultaneously and lots of projectiles flying around. So the most important thing is, physics and collision computation must be very fast.

Could you please point me in the right direction? Idea I'm elaborating on is some kind of 3D tiles, with every unit's position being x,y index of tile + elevation (e.g unit staning on the hill or on the fortress wall). the smallest unit will occupy for examle one tile horizonally and 5 vertically. With every tile having 3x3x1 aspect ratio (e.g. 15x15 horizontally and 5 pixels height).

How realistic is this? How would you approach this? Are there any 3d physics/collision engines which are fast enough for such application?

Hope for your help Alex

# Answer
> 8 votes
The main thing to remember when dealing with an RTS game is that collision detection isn’t the same kind of animal it is in a FPS. The game, not the player, determines if a unit actually hits its target, so you’re not worrying about things like "*If a shot goes between his legs, how do we know it didn’t hit him?*" but rather "*we decided that he hit him, so make the shot look like it hit him.*" Units attacking one another usually amounts to "*Is the unit in range? Does it have line of sight? Okay, animate the attack and calculate damage.*" Most RTS games don’t even taken into account a "chance to hit" all attacks hit, and damage is random within some range which expresses the idea of "how on target" the shot was. This means that for combat you’re usually just considering ray-polygon intersections to check that the units have line of sight. This can be performed against a very simplified version of the map geometry using bounding boxes (A single box for each unit if you want them to be included, rough outline of the terrain and map elements). There are a huge number of tutorials on this, just search for *Ray-Box Intersection*, *Ray-Polygon Intersection* and *Bounding Box Collision Detection* to find out more.

Movement in RTS is generally the more complicated bit, for the same reason combat is simpler. The game, not the player, has to navigate the terrain. Generally this is accomplished by creating a kind of "map of the map" which defines areas as passable, impassable, (and possibly shoot-through-able or not which can be used to further simplify line of site determinations). This map is then used to plot paths for the units. Google *Navigation Mesh* for details on how the “map of the map” is constructed. Google *Pathfinding* for more details on how to calculate and plot paths. *Dijkstra's Algorithm* and *A** are two common pathfinding algorithms. Pathfinding is a part of the mathematics field known as *Graph Theory* if you’re interesting in reading up on the topic more broadly.

As for physics, except in AAA titles there usually isn’t much real physics implemented beyond basic velocity/acceleration calculations for movement. You can store values in the passable areas of the map to indicate high and slow the unit’s velocity when they are moving from low to high terrain, or through special terrain. When units are damaged they are playing a hard-coded animation of “being flung through the air” or “tossed aside” etc, based on the outcomes of the combat calculations.

If you have any specific questions just let me know.

---
Tags: 3d, collision-detection, physics, tiles, rts
---


# Question
Title: Change back to initial value of rotation?
I have a sprite that I can rotate and I wonder if there is a way to change the rotation back to the initial value?

# Answer
Set the rotation of the sprite to 0:

```
sprite.Rotation = 0;

```
> 2 votes

---
Tags: xna
---


# Question
Title: Can anyone explain step-by-step how the as3isolib depth-sorts isometric objects?
The library manages to depth-sort correctly, even when using items of non-1x1 sizes. I took a look through the code but it's a big project to go through line by line!

There are some questions about the process such as:

1. How are the x, y, z values of each object defined? Are they the center points of the objects or something else?
2. I noticed that the IBounds defines the bounds of the object. If you were to visualise a cuboid of 40, 40, 90 in size, where would each of the IBounds metrics be?

I would like to know how as3isolib achieves this although I would also be happy with a generalised pseudo-code version.

At present I have a system that works 90% of the time but in cases of objects that are along the same horizontal line, the depth is calculated as the same value.

The depth calculation currently works like this:

x = object horizontal center point y = object vertical center point

originX and Y = the origin point relative to the object so if you want the origin to be the center, the value would be originX = 0.5, originY = 0.5. If you wanted the origin to be vertical center, horizontal far right of the object it would be originX = 1.0, originY = 0.5. The origin adjusts the position that the object is transformed from.

AABB\_width = The bounding box width. AABB\_height = The bounding box height.

depth = x + (AABB\_width * originX) + y + (AABB\_height * originY) - z;

This generates the same depth for all objects along the same horizontal x.

# Answer
> 5 votes
**Z-sorting** or **depth-sorting** in **as3isolib** is calculated (by default) in the following class:

```
public class DefaultSceneLayoutRenderer implements ISceneLayoutRenderer

```

that can be found in:

```
package as3isolib.display.renderers

```

The code inside `DefaultSceneLayoutRenderer` itself is actually not too long (only 200 hundred lines of code w/comments and all) but quite clever. An outline of what it does is:

**1 -** Loop through all objects (children) in the scene, see what objects are behind child\[i\] (by looping again) and store them into an array or dictionary of dependencies. This is achieved in the following code:

```
public function renderScene (scene:IIsoScene):void
{

dependency = new Dictionary();

var children:Array = scene.displayListChildren;
var max:uint = children.length;

for (var i:uint = 0; i < max; ++i)
{
  var behind:Array = [];

  var objA:IsoDisplayObject =children[i];

  var rightA:Number = objA.x + objA.width;
  var frontA:Number = objA.y + objA.length;
  var topA:Number = objA.z + objA.height;

  for (var j:uint = 0; j < max; ++j)
  {
    var objB:IsoDisplayObject = children[j];

    //skipped code for collision detection...

    // See if B should go behind A
    // simplest possible check, interpenetrations also count as "behind"
    if (
      (objB.x < rightA) &&
      (objB.y < frontA) &&
      (objB.z < topA) &&
      (i !== j)
    )
    {
      behind.push(objB);
    }

  }//end nested loop

  dependency[objA] = behind;

}//end loop

//...
//see point 2

```

**2 -** Set the childrens' depth, using dependency ordering. Checking the dependency dictionary object, we place all the children that are inside it BEFORE ( = at a lower depth, thus they will be rendered behind) and we do this recursively to put each child's dependency list behind it. This is done here:

```
//reset depth between calls
depth = 0;

//visited is a dictionary of objects to make sure we don't add the same child twice
for each (var obj:IsoDisplayObject in children)
  if (true !== visited[obj] )
    place(obj);

// Clear out temporary dictionary
visited = new Dictionary();

}//end function renderScene

/**
* function place
* Dependency-ordered depth placement of the given objects and its dependencies.
*/
private function place(obj:IsoDisplayObject):void
{
  visited[obj] = true;

  for each(var inner:IsoDisplayObject in dependency[obj])
    if(true !== visited[inner])
      place(inner);

  if (depth != obj.depth)
  {
    scene.setChildIndex(obj, depth);
  }

  ++depth;
}

```

Note that this is naive z-sorting, so it's far from perfect. You can create your own class to "customize" z-sorting for your project using **as3isolib**, for that you'd only need to implement ISceneLayoutRenderer and assign it as your as3isolib scene `layoutRenderer`:

```
var myRenderer:CustomLayoutRenderer = new CustomLayoutRenderer();

scene.layoutRenderer = myRenderer;

```

Hope this helps!

---
Tags: actionscript-3, isometric
---


# Question
Title: How to balance damage dealt by opponents in a strategy game?
Consider the following situation: you are developing a RTS, with different races opposing each other, with different kinds of abilities (e.g. Starcraft). How should I go about in balancing the damage, speed, cool down times etc. of the respective troops/units? Are there any good resources on that or sort of test-beds?

# Answer
> 6 votes
Balancing is really an art form, but it comes down to balancing rock vs paper vs scissors, meaning that in-general rock should beat scissors, scissors should beat paper, and paper should beat rock.

How easily rock defeats paper can be dependent upon other advantages and disadvantages of buying a rock, such as how it fares against a paperclip or a tree, how far you can throw rock, and how much it cost you to get that rock.

That being said, balancing in-general is **very** specific to the game, and there is rarely a place where you can plug in values, and be given a straight answer (such as 'overpowered'). There *are* some factors that can play a very important role, though. In many games, Damage Per Second (DPS) can provide you with almost everything you need to know about how powerful a unit is.

Using values like DPS, it's possible to create a formula that will give you an idea of how powerful a unit is. For example, a unit's 'effectiveness, could be the value that combines a unit's 'Power', 'Utility', and 'Defense'. However, telling you *how* to get these values is (as I mentioned before), **very** specific to the game you are making.

---
Tags: game-design, game-mechanics, rts
---


# Question
Title: How much would it cost to produce a game engine, and website to sell it from?
I've been considering for a long time how much it would cost to hire developers and programers to make a game engine and website for the engine? Posibly even some graphic designers for game engine textures, or maybe some concept art, etc. What would be a ball park estimate of all this?

Edit: It would be for any platform, and for a variety of 3D Gaming Types; RPG, FPS, etc. It's capabilities would be as far as making a complete game from scratch, maps, scripts, etc.

Edit: For the sake of an estimation, let say the platform was limited to PC and Mac.

# Answer
Lets use Unity3D as our reference "game engine company" It's nice because it's fairly recent, it's open about its history, and it makes an engine without also making games. It's also fairly close to your need to run on multiple platforms and support different game types.

Lets start with some numbers from this answer https://gamedev.stackexchange.com/a/4531/2624:

> Total Loaded cost to employer per developer per month **8000 to 15000**

History - http://unity3d.com/history.html

By the time the Unity released their first game, it was 3 years of basement-dwelling for 3 full-time developers. By the time Unity released Unity version 1, it was a team of 7. So version 1 of Unity, you could calculate at 15 person-years or so. At 10k per month of employer expenses, we can get a nice round estimate of **$1,800,000**

By now, Unity is on version 4. Here's a picture of them: http://unity3d.com/company/people/ It would cost significantly more than just a couple million dollars to replicate the current state of Unity.
> 10 votes

---
Tags: pricing
---


title: Game loop alternatives for efficiency

text:
# Question
Title: Game loop alternatives for efficiency
Understand where I'm coming from - I've been taught that a game is implemented something like this (pseudocode):

```
while (!win_condition)
{
   waitforinput();
   updategraphics();
   //etc..
}
exit();

```

Is there another way to implement the "game loop" without limiting the game to finite "turns"?

This

```
while (true)

```

business seems to eat a lot of CPU, especially for how simple a game I'm making!

# Answer
If your game loop is not throttled to a given framerate it will run as fast as it can. Do a google search for fixed time game loop and you'll find in depth comparisons on how these work.

Basically you measure how long your loop iteration took to complete compared to how much time you have per frame at your given frame rate (e.g. at 25fps you'll have 1/25th of a second to complete your game loop while maintaining your frame rate) and sleep for the remainder of time.

Another approach that can work if your game is event driven and has static graphics between events is to poll for user input every so often and then sleep.
> 2 votes

# Answer
That really is the best way. Even with a multi-threaded engine, you want to use task batching, so your main loop will still be "update system A, then system B, etc."

So far as eating up CPU, you definitely want to be conscious of that, especially on mobile gaming (but even for PC gaming due to the rising popularity of mobile PCs).

First, always use sync-to-vblank. That'll keep your game loop from running faster than the display. You can use a custom frame rate controller if vblank syncing is for some reason not usable (or if you are using triple buffering). Basically put a microsecond-accurate sleep (not a busy loop) at the end of your loop after doing the buffer swap in order to keep the game from running faster than you need it to.

You can also replace the part that queries system events (the Win32 message pump, for instance) between blocking and non-blocking when you go into screens that have no animation running when the player isnt doing anything, such as a pause screen or the main menu.
> 1 votes

# Answer
There are ways to handle the loop differently but since you said your game was so simple, the standard loop is probably what you want. Other ways would probably make the code more complex than what I'm guessing you are interested in.

Its true that the while loop has some issues, like how it will run at different speeds depending on the CPU, but its kinda the de facto standard.

That and it's not really the while loop that eats a lot the cpu, it's what you do in the loop that makes the most impact. You are always going to want a loop for any graphical game because there is no easier way to constantly check the exit condition of your game and update graphics, physics, input, etc.
> 1 votes

# Answer
Dosen't matter. The win\_condition will be true most of the time. It is the same of putting 'true' directly. And the 'true' approach saves memory, one less variable.
> 0 votes

---
Tags: game-design, game-loop
---


# Question
Title: How create a respawn area in a tiled map
I'm creating a RPG game, I need to create a monster respawn area like the Pokemon games where if I walk through the long grass areas a Pokemon can appear. I already created the battle scene, I've seen examples of tile collision with solid objects but I don't know how create a collision action with passable objects.

# Answer
> 4 votes
I suppose you could call it a collision, but it's more like an intersection. You can create a trigger zone that activates when the player enters it. A simple way of doing that would just create a list of these zones, then check to see if the player is inside them every frame or when the player moves. A zone is just two points, a min and a max. Then you can check when something is inside like so:

```
public boolean contains(float x, float z) {
    return (x >= minX && x < maxX &&
        z >= minZ && z < maxZ);
}

```

# Answer
> 0 votes
Finally i got how create the respawn zone, i create 2 arrays of tmxmap objects and extract is properties in the example i create wall(unwalkable zone) and isMonsterRespawn zone, where if the player collide with that zone certain action happens, in my example case the respawn zone change the color tile. There i can set an action that cant send my character to the battle scene with a randomly chance:

```
private void createUnwalkableObjects(TMXTiledMap map,final AnimatedSprite pl) {

 for(final TMXObjectGroup group: this.mTMXTiledMap.getTMXObjectGroups()) {

   if(group.getTMXObjectGroupProperties().containsTMXProperty("wall", "true")){
             // This is our "wall" layer. Create the boxes from it
   for(final TMXObject object : group.getTMXObjects()) {

                final Rectangle rect = new Rectangle(object.getX(), object.getY(),object.getWidth(), object.getHeight());
                rect.setVisible(false);
                final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0, 0, 1f);
                PhysicsFactory.createBoxBody(this.mPhysicsWorld, rect, BodyType.StaticBody, boxFixtureDef);
                mScene.attachChild(rect);
             }
         }if(group.getTMXObjectGroupProperties().containsTMXProperty("IsMonsterSpawnArea", "true")){
             // This is our "wall" layer. Create the boxes from it
             for(final TMXObject object : group.getTMXObjects()) {
                final Rectangle rect = new Rectangle(object.getX(), object.getY(),object.getWidth(), object.getHeight());
    rect.setVisible(true);
    mScene.attachChild(rect);
    mScene.registerUpdateHandler(new IUpdateHandler() {
                    @Override
                    public void reset() {

}

                    @Override
                    public void onUpdate(final float pSecondsElapsed) {
                        if(pl.collidesWith(rect)){
//here the action when the player collides the zone
                            rect.setColor(1, 0, 1);}else{
                                rect.setColor(1, 0, 0);
                            }
                        }

                });

             }
         }
     }

}

```

---
Tags: android, collision-detection, tiles, andengine
---