title: How to make a "GUI In Game"?

text:
# Question
Title: How to make a "GUI In Game"?
My game is very GUI based, the way how it works is that I have a GUI class, which contains the basic GUI elements, a parent GUI object, and a copy of the main game's class object. The game starts out with the main GUI, which is the main menu, then when it wants to it takes something like the in game GUI, creates a object with the main menu's copy of the game and then the main menu object itself using *this* as the parent GUI. So when the in game GUI wants to, it can call back for the parent GUI to be used again.

Here is where the issue lays, the in game GUI needs to be a GUI, but also needs to contain this such as the level it's playing, the player, and all those things. How is this done?

Should I have approached my GUI based system differently? Because I can't somehow figure out of I would implement such a GUI without errors. How do you approach this? Or how would you approach this?

# Answer
You should clearly separate GUI (view) from the actual game state (model). GUI just shows the model to the player (in one way or another) and lets the player control it, but the model itself is solid enough to know everything it needs (level, player, etc). The GUI should know only things GUI needs, which model does not care about (e.g. controls positions).
> 6 votes

# Answer
The answer to your specific question, how does the GUI know about the level being played, is: it doesn't.

The GUI displays everything it's being told to display, but it doesn't have any information about what that data actually is.

A common approach is to use a message system to pass messages from one component to another. When the `LevelLoader` has finished loading a level, it creates a message:

```
<MessageEnvelope type="LevelLoaded">
    <Identifier>1</Identifier>
    <Name>Big spooky forest</Name>
    <Attempt>33</Attempt>
</MessageEnvelope>

```

I'm using XML here, but you can use whatever you like. Personally, I prefer Protobuf.

The message system approaches all of its listeners with this message until the GUI says: yup, that one's for me. The GUI then extracts the `Name` element from the XML and uses it to display the level's name.

There are two things to keep in mind here: the GUI doesn't know the `LevelLoader` class exists (decoupling), only that it can receive messages from the `MessageSystem`. And the `LevelLoader` doesn't know that the GUI exists, only that it has to send a message to the `MessageSystem` when the level is done loading.

Because both are oblivious to each other, it's very easy to swap out implementations.
> 1 votes

---
Tags: java, architecture, gui, game-state
---


# Question
Title: Drawing the same scene with perspective then orthographic projections
I have a scene that I'm rendering first with a perspective matrix. I then want to rerender it in a different viewport using an orthographic matrix for a top-down 2D view of the scene. I think I may be missing something because I get nothing rendered with the orthographic projection.

To setup the ortho projection I create the matrix with the near/far set to (-1,1) (not sure how it affects rendering) and then move the camera up and pitch it 90 degrees and rerender the vertices without modification.

I'm using OpenGL4 with glm to produce the matrices.

# Answer
> -1 votes
When rendering with an ortographic projection, you need to set your model view matrix to identity.

To learn more about projection matrices, I'd suggest reading this article: http://www.songho.ca/opengl/gl\_projectionmatrix.html

---
Tags: opengl, mathematics, rendering, camera
---


title: Farseer: RemoveBody is not working

text:
# Question
Title: Farseer: RemoveBody is not working
I want to remove bodies after they touched the character(playerrect). But the bodies get not removed. I set a breakpoint in the following line but it doesn't get yellow:

```
world.RemoveBody(world.BodyList[i]);

```

What is wrong? Why is the breakpoint not getting released?

How can I remove a body?

```
bool Player_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
{
  if (fixtureB.CollisionCategories == Category.Cat1)
  {
    fixtureB.UserData = "RemoveMe";
  }
  return true;
}

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

playerrect.OnCollision += Player_OnCollision;

reccoin = BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f);
reccoin.BodyType = BodyType.Static;
reccoin.Position = new Vector2(0.96f, 4.16f);
reccoin.IsSensor = true;
reccoin.CollisionCategories = Category.Cat1;

 protected override void Update(GameTime gameTime)
 {
   float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
   world.Step(Math.Min(elapsed, (1f / 60f)));
   for (int i = world.BodyList.Count - 1; i >= 0; i--)
   {
     if (world.BodyList[i].UserData == "RemoveMe")
     world.RemoveBody(world.BodyList[i]);
   }

 base.Update(gameTime);
 }

//Drawing:
spriteBatch.Draw(coinSprite, ConvertUnits.ToDisplayUnits(reccoin.Position),
                                   null,
                                   Color.White, reccoin.Rotation, new Vector2(coinSprite.Width / 2.0f, coinSprite.Height / 2.0f), 1f,
                                   SpriteEffects.None, 0f);

```

# Answer
> 0 votes
It would be easier and faster to just remove the fixture on collision, instead of looping and checking for a string you set earlier.

I would update the OnCollision function as follows:

```
bool Player_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
{
  //If category group 1
  if (fixtureB.CollisionCategories == Category.Cat1)
     world.RemoveBody(fixtureB);

  return true;
}

```

And then your Update method:

```
protected override void Update(GameTime gameTime)
{
   float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
   world.Step(Math.Min(elapsed, (1f / 60f)));
   base.Update(gameTime);
}

```

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


# Question
Title: Shader registers for different graphics card
The title is not very explicative, so i'll try to make myself clear. I have two "working"(on which i work on) PCs : a desktop that runs an NVIDIA GT440 an a laptop with a RADEON HD 4650. I have a shader for multipass rendering that uses both POSITION0 and POSITION1 registers for the vertex shader output :

```
struct VS_OUT
{
    float4 Position : POSITION0;
    float4 WorldPosition : POSITION1;

   // More variables for normal mapping and more
};

```

This code works just fine on my desktop, but when i run it on my laptop the rendering is screwed. I finally tracked down the problem to the POSITION1 output parameter, if i change it to TEXCOORD0 it works. Now ... i don't like to do things i do not understand, so i'd like to understand WHY it happens.

It's something GPU related for sure, but i'd be glad if you could link me some papers, articles or anything that explains how the registers work, and why not... even something in-deep about the programmable pipeline.

Thank you for your time and happy coding!

# Answer
I think the problem is with the semantics used. As far as I know, pixel shader can only recieve SV\_POSITION - if talking about POSITION (which is filled usualy by vertex shader POSITION0 semantics) The only user-defined semantics you can recieve in pixel shader are:

* **COLOR\[n\]**
* **TEXCOORD\[n\]**

The behavior you're describing is because these are two different implementations of DirectX and reading POSITION0 semantics in pixel shader is not defined by DirectX standard.

See this page for semantics details:

http://msdn.microsoft.com/en-us/library/windows/desktop/bb509647%28v=vs.85%29.aspx#PS
> 2 votes

---
Tags: shaders, hlsl, fragment-shader, pipeline
---


# Question
Title: Continuous / speed affected sound effects. What is the industries de-facto solution?
There are various types of audio material we require in games.

For instance, **footsteps** \- these are very straight forward.
We take some *boinking* sounds over metal, plastic, concrete and add to our asset library.

Now, in a good game, based on player models locomotion, once foot collides with surface, we play the sound - just from start to end, let it complete. We might lower the volume, and/or fade it out in case we need it to be more silent (like, when we didn't make a full step).

In a little lesser game, we could simply play the sound once every **n** ticks of walk.

The result in both cases add the depth to the game that is required to make the impression that the player is *really walking*.

Now, what I have problems with, is, grasping the idea behind continuous and speed affected sounds.

## Continuous

With continuous sounds I think of *Rocket Launcher's rocket propulsion*, *Dash abilities sound feedback* and such.

You might ask, what's so different for those vs. **footsteps**? Well, I see two possible solutions:

* A very long, continuous sound that is faded out / cut off whenever the rocket explodes, or the dash ends.
* A very short, precisely cut out sound fragment, that can be looped for as long as you wish (this could possibly be enhanced, by once in a while nipping in or overlaying another short with different tone or what not).

And I think some of you might have something else up your sleeve.

## Speed affected

With speed affected effects I think of engine sounds, like those we hear in *Need for Speed* franchise and such.

With this, the only solution I have in mind is *smart* overlay of multiple set of sounds with different lengths.

---

For both, the continuous and speed affected I have left out real-time software intervention, which I think is rarely applied due to more consumed CPU cycles, though, I may be wrong.

And so, the question is:

### What is the industries de-facto solution to create and manipulate such effects?

# Answer
Almost all sound libraries (DirectSound, XACT, XAudio2, OpenAL, Core Audio, etc.) support changing the playback rate of your sounds. By doing this, you will effectively be changing the sound pitch, so you can use this for example, to make car engines sound higher programmatically as they move faster.

Also, many libraries support more advanced sound effects. Mixing and Reverb are very common, but Doppler shifting, High-pass, Lo-pass filters, Equalizers and many other modules are available for you to modify your sounds in runtime, with varying qualities and delays.

Make sure you check the documentation of whatever library you're using, to see which effects are available.

(I hope that with my answer you understand why asking for a "de-facto solution" is not appropriate for your question)
> 3 votes

---
Tags: assets, sound, audio, asset-creation
---


# Question
Title: What's a good alternative to colored tiles to account for color blindness?
I have a game with tiles. Each tile is a number, and each number is one of six colors. The color is important to the game play, and I want to make the game available to those who are color blind.

What would be a good representation for these colors so people with color blindness can play as well?

# Answer
> 14 votes
I don't know if there exists a set of colors that all people will be able to differentiate, whether or not they have any color-blindness.

It might be a better idea to use an additional indicator alongside color. I know that the Ticket To Ride boardgame uses a symbol on each of the different color cards, so that if someone can't tell the difference between two colors, they can look at the card and the board and see if the symbols match.

Another option would be to use patterns on the tiles. Stripes, wavy lines, cross-hatching, dots or diamonds are all different enough that a player could be able to tell them apart even if they can't tell what color they are looking at.

# Answer
> 4 votes
A color Blind person sees as shown on the picture below. I would say that you should leave out the green or purple colors, and make sure that the difference between each colour is big. If you need the players to distinquish the tiles for their colours, I'd simply make them use different types of textures straight lines, horizontal lines, circles, crossed lines, no lines etc.

There are different types of that illness, and choosing the right color would never suit everyone. http://simple.wikipedia.org/wiki/Color\_blindness

The image below shows the most common color blindnes, whch is Red/Green color blindness.

> From Wikipedia:
>
> There are two kinds of red-green color blindness: protanopia or deuteranopia. **Deuteranopia is the most common form of color blindness, between five and ten percent of males suffer from it**. Those affected have trouble telling the difference between red and green. As seen by protanopes (people suffering from protanopia), red is darkened. Most often, this is because they lack the receptors for long (protanopia) or medium (deuteranopia)-length light waves or because these receptors have changed their sensitivity.

# Answer
> 4 votes
Silhouettes. Always silhouettes. Even if you don't care about color-blindness, every distance game element *needs* a distinct silhouette. Not just a glyph on the element, but a distinctly visual black-and-white outline.

For a game with tiles, consider non-square shapes. They can be square-ish, but have trapezoids and the like as well. Do not rely on the numbers. Do not rely on colors. Make the primary identification method the silhouette.

# Answer
> 4 votes
This adds to Sean Middleditch's answer. The best you can do is to check for relative luminance contrast to distinguish each tile/shape. You can look up relative luminance of a color here (the Lum value). A good contrast distance is 30% to 40%.

# Answer
> 2 votes
Most colour blinds are dichromats, they can actually see some colour, but typically lack either red or green receptors. If you make a set of colours where the red and the green values are the same and the colours are clearly differentiable to you they should be so for most colour blinds as well.

If you only have a few colours, different shades of grey can work well enough for full colour blinds, but 6 different shades is probably a bit over the top. So you will have to use shapes or patterns for these.

I think shapes could work really well for the problem at hand, make 6 simple yet clearly distinguishable shapes, draw them either black or different colours on the tiles and put a white number on top.

No matter what you choose to do, ask some colour blinds how they like it and be prepared to tweak your solutions accordingly.

# Answer
> 2 votes
In designing a game with this in mind, I have used shapes that correspond to the colors. You can think of this in terms of "suits", with the numbers being "ranks", similar to a card game. Even if someone couldn't tell red from black, they could still tell a 4 of clubs from a four of diamonds by the shapes.

To make it easier for those with varying degrees of color blindness, you can make the colors used well differentiated in lightness. Someone who sees light red and light green as the same color can often tell the difference between dark red and light green.

---
Tags: game-design, color, accessibility
---


# Question
Title: How can I move a character based on a the background?
I want to know how can I move the following character just in predefined areas as shown in the bg.jpg file

character

bg

I'm using HTML 5 canvas

Best regards,

# Answer
> 1 votes
You'll want to set up a collision map. IE take your background picture and make a copy of it. Color everything that is passable with one color (IE: black) and everything that is impassible with another color (IE: white). Then when doing collision detection, check your characters future position against your collision map, if your characters box contains any white, then their position is blocked.

Note: This is only one possible option. There are many other ways to do this I'm sure.

# Answer
> -1 votes
Use *esel.js* and do something like this:

```
(function (window) {
    // Constants for controling horizontal movement
    var MoveAcceleration = 13000.0;
    var MaxMoveSpeed = 1750.0;
    var GroundDragFactor = 0.48;
    var AirDragFactor = 0.58;

    // Constants for controlling vertical movement
    var MaxJumpTime = 0.35;
    var JumpLaunchVelocity = -5000.0;
    var GravityAcceleration = 1800.0;
    var MaxFallSpeed = 550.0;
    var JumpControlPower = 0.14;

    var globalTargetFPS = 17;

    var StaticTile = new Tile(null, Enum.TileCollision.Passable, 0, 0);

    // imgPlayer should be the PNG containing the sprite sequence
    // level must be of type Level
    // position must be of type Point
    function Player(imgPlayer, level, position) {
        this.initialize(imgPlayer, level, position);
    }

    // Using EaselJS BitmapSequence as the based prototype
    Player.prototype = new BitmapAnimation();

    Player.prototype.IsAlive = true;
    Player.prototype.HasReachedExit = false;

    /// <summary>
    /// Gets whether or not the player's feet are on the ground.
    /// </summary>
    Player.prototype.IsOnGround = true;

    // constructor:
    //unique to avoid overiding base class
    Player.prototype.BitmapAnimation_initialize = Player.prototype.initialize;

    /// <summary>
    /// Constructors a new player.
    /// </summary>
    Player.prototype.initialize = function (imgPlayer, level, position) {
        var width;
        var left;
        var height;
        var top;
        var frameWidth;
        var frameHeight;

        var localSpriteSheet = new SpriteSheet({
            images: [imgPlayer], //image to use
            frames: { width: 64, height: 64, regX: 32, regY: 64 },
            animations: {
                walk: [0, 9, "walk", 4],
                die: [10, 21, false, 4],
                jump: [22, 32, false],
                celebrate: [33, 43, false, 4],
                idle: [44, 44]
            }
        });

        SpriteSheetUtils.addFlippedFrames(localSpriteSheet, true, false, false);

        this.BitmapAnimation_initialize(localSpriteSheet);
        this.level = level;
        this.position = position;
        this.velocity = new Point(0, 0);
        this.previousBottom = 0.0;

        this.elapsed = 0;

        this.isJumping = false;
        this.wasJumping = false;
        this.jumpTime = 0.0;

        frameWidth = this.spriteSheet.getFrame(0).rect.width;
        frameHeight = this.spriteSheet.getFrame(0).rect.height;

        // Calculate bounds within texture size.
        width = parseInt(frameWidth * 0.4);
        left = parseInt((frameWidth - width) / 2);
        height = parseInt(frameWidth * 0.8);
        top = parseInt(frameHeight - height);
        this.localBounds = new XNARectangle(left, top, width, height);

        // set up a shadow. Note that shadows are ridiculously expensive. You could display hundreds
        // of animated monster if you disabled the shadow.
        if (enableShadows)
            this.shadow = new Shadow("#000", 3, 2, 2);

        this.name = "Hero";

        // 1 = right & -1 = left & 0 = idle
        this.direction = 0;

        // starting directly at the first frame of the walk_right sequence
        this.currentFrame = 66;

        this.Reset(position);
    };

    /// <summary>
    /// Resets the player to life.
    /// </summary>
    /// <param name="position">The position to come to life at.</param>
    Player.prototype.Reset = function (position) {
        this.x = position.x;
        this.y = position.y;
        this.velocity = new Point(0, 0);
        this.IsAlive = true;
        this.level.IsHeroDied = false;
        this.gotoAndPlay("idle");
    };

    /// <summary>
    /// Gets a rectangle which bounds this player in world space.
    /// </summary>
    Player.prototype.BoundingRectangle = function () {
        var left = parseInt(Math.round(this.x - 32) + this.localBounds.x);
        var top = parseInt(Math.round(this.y - 64) + this.localBounds.y);

        return new XNARectangle(left, top, this.localBounds.width, this.localBounds.height);
    };

    /// <summary>
    /// Handles input, performs physics, and animates the player sprite.
    /// </summary>
    /// <remarks>
    /// We pass in all of the input states so that our game is only polling the hardware
    /// once per frame. We also pass the game's orientation because when using the accelerometer,
    /// we need to reverse our motion when the orientation is in the LandscapeRight orientation.
    /// </remarks>
    Player.prototype.tick = function () {
        // It not possible to have a predictable tick/update time
        // requestAnimationFrame could help but is currently not widely and properly supported by browsers
        // this.elapsed = (Ticker.getTime() - this.lastUpdate) / 1000;
        // We're then forcing/simulating a perfect world
        this.elapsed = globalTargetFPS / 1000;

        this.ApplyPhysics();

        if (this.IsAlive && this.IsOnGround && !this.HasReachedExit) {
            if (Math.abs(this.velocity.x) - 0.02 > 0) {
                // Checking if we're not already playing the animation
                if (this.currentAnimation.indexOf("walk") === -1 && this.direction === -1) {
                    this.gotoAndPlay("walk");
                }
                if (this.currentAnimation.indexOf("walk_h") === -1 && this.direction === 1) {
                    this.gotoAndPlay("walk_h");
                }
            }
            else {
                if (this.currentAnimation.indexOf("idle") === -1 && this.direction === 0) {
                    this.gotoAndPlay("idle");
                }
            }
        }

        // Clear input.
        this.isJumping = false;
    };

    /// <summary>
    /// Updates the player's velocity and position based on input, gravity, etc.
    /// </summary>
    Player.prototype.ApplyPhysics = function () {
        if (this.IsAlive && !this.HasReachedExit) {
            var previousPosition = new Point(this.x, this.y);

            // Base velocity is a combination of horizontal movement control and
            // acceleration downward due to gravity.
            this.velocity.x += this.direction * MoveAcceleration * this.elapsed;
            this.velocity.y = Math.clamp(this.velocity.y + GravityAcceleration * this.elapsed, -MaxFallSpeed, MaxFallSpeed);

            this.velocity.y = this.DoJump(this.velocity.y);

            // Apply pseudo-drag horizontally.
            if (this.IsOnGround) {
                this.velocity.x *= GroundDragFactor;
            }
            else {
                this.velocity.x *= AirDragFactor;
            }

            // Prevent the player from running faster than his top speed.
            this.velocity.x = Math.clamp(this.velocity.x, -MaxMoveSpeed, MaxMoveSpeed);

            this.x += this.velocity.x * this.elapsed;
            this.y += this.velocity.y * this.elapsed;
            this.x = Math.round(this.x);
            this.y = Math.round(this.y);

            // If the player is now colliding with the level, separate them.
            this.HandleCollisions();

            // If the collision stopped us from moving, reset the velocity to zero.
            if (this.x === previousPosition.x) {
                this.velocity.x = 0;
            }

            if (this.y === previousPosition.y) {
                this.velocity.y = 0;
            }
        }
    };

    /// <summary>
    /// Calculates the Y velocity accounting for jumping and
    /// animates accordingly.
    /// </summary>
    /// <remarks>
    /// During the accent of a jump, the Y velocity is completely
    /// overridden by a power curve. During the decent, gravity takes
    /// over. The jump velocity is controlled by the jumpTime field
    /// which measures time into the accent of the current jump.
    /// </remarks>
    /// <param name="velocityY">
    /// The player's current velocity along the Y axis.
    /// </param>
    /// <returns>
    /// A new Y velocity if beginning or continuing a jump.
    /// Otherwise, the existing Y velocity.
    /// </returns>
    Player.prototype.DoJump = function (velocityY) {
        // If the player wants to jump
        if (this.isJumping) {
            // Begin or continue a jump
            if ((!this.wasJumping && this.IsOnGround) || this.jumpTime > 0.0) {
                if (this.jumpTime == 0.0) {
                    this.level.levelContentManager.playerJump.play();
                }

                this.jumpTime += this.elapsed;
                // Playing the proper animation based on
                // the current direction of our hero
                if (this.direction == 1) {
                    this.gotoAndPlay("jump_h");
                }
                else {
                    this.gotoAndPlay("jump");
                }
            }

            // If we are in the ascent of the jump
            if (0.0 < this.jumpTime && this.jumpTime <= MaxJumpTime) {
                // Fully override the vertical velocity with a power curve that gives players more control over the top of the jump
                velocityY = JumpLaunchVelocity * (1.0 - Math.pow(this.jumpTime / MaxJumpTime, JumpControlPower));
            }
            else {
                // Reached the apex of the jump
                this.jumpTime = 0.0;
            }
        }
        else {
            // Continues not jumping or cancels a jump in progress
            this.jumpTime = 0.0;
        }
        this.wasJumping = this.isJumping;

        return velocityY;
    };

    /// <summary>
    /// Detects and resolves all collisions between the player and his neighboring
    /// tiles. When a collision is detected, the player is pushed away along one
    /// axis to prevent overlapping. There is some special logic for the Y axis to
    /// handle platforms which behave differently depending on direction of movement.
    /// </summary>
    Player.prototype.HandleCollisions = function () {
        var bounds = this.BoundingRectangle();
        var leftTile = Math.floor(bounds.Left() / StaticTile.Width);
        var rightTile = Math.ceil((bounds.Right() / StaticTile.Width)) - 1;
        var topTile = Math.floor(bounds.Top() / StaticTile.Height);
        var bottomTile = Math.ceil((bounds.Bottom() / StaticTile.Height)) - 1;

        // Reset flag to search for ground collision.
        this.IsOnGround = false;

        // For each potentially colliding tile,
        for (var y = topTile; y <= bottomTile; ++y) {
            for (var x = leftTile; x <= rightTile; ++x) {
                // If this tile is collidable,
                var collision = this.level.GetCollision(x, y);
                if (collision !== Enum.TileCollision.Passable) {
                    // Determine collision depth (with direction) and magnitude.
                    var tileBounds = this.level.GetBounds(x, y);
                    var depth = bounds.GetIntersectionDepth(tileBounds);
                    if (depth.x !== 0 && depth.y !== 0) {
                        var absDepthX = Math.abs(depth.x);
                        var absDepthY = Math.abs(depth.y);

                        // Resolve the collision along the shallow axis.
                        if (absDepthY < absDepthX || collision == Enum.TileCollision.Platform) {
                            // If we crossed the top of a tile, we are on the ground.
                            if (this.previousBottom <= tileBounds.Top()) {
                                this.IsOnGround = true;
                            }

                            // Ignore platforms, unless we are on the ground.
                            if (collision == Enum.TileCollision.Impassable || this.IsOnGround) {
                                // Resolve the collision along the Y axis.
                                this.y = this.y + depth.y;

                                // Perform further collisions with the new bounds.
                                bounds = this.BoundingRectangle();
                            }
                        }
                        else if (collision == Enum.TileCollision.Impassable) // Ignore platforms.
                        {
                            // Resolve the collision along the X axis.
                            this.x = this.x + depth.x;

                            // Perform further collisions with the new bounds.
                            bounds = this.BoundingRectangle();
                        }
                    }
                }
            }
        }

        // Save the new bounds bottom.
        this.previousBottom = bounds.Bottom();
    };

    /// <summary>
    /// Called when the player has been killed.
    /// </summary>
    /// <param name="killedBy">
    /// The enemy who killed the player. This parameter is null if the player was
    /// not killed by an enemy (fell into a hole).
    /// </param>
    Player.prototype.OnKilled = function (killedBy) {
        this.IsAlive = false;
        this.velocity = new Point(0, 0);

        // Playing the proper animation based on
        // the current direction of our hero
        if (this.direction === 1) {
            this.gotoAndPlay("die_h");
        }
        else {
            this.gotoAndPlay("die");
        }

        if (killedBy !== null && killedBy !== undefined) {
            this.level.levelContentManager.playerKilled.play();
        }
        else {
            this.level.levelContentManager.playerFall.play();
        }
    };

    /// <summary>
    /// Called when this player reaches the level's exit.
    /// </summary>
    Player.prototype.OnReachedExit = function () {
        this.HasReachedExit = true;
        this.level.levelContentManager.exitReached.play();

        // Playing the proper animation based on
        // the current direction of our hero
        if (this.direction === 1) {
            this.gotoAndPlay("celebrate_h");
        }
        else {
            this.gotoAndPlay("celebrate");
        }
    };

    window.Player = Player;
} (window));`

```

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


# Question
Title: High-definition Full-motion background system in XNA
I'm mostly just working on this as a hobbyist thing, but here's my problem: I got a bit excited over finding the 'Video' and 'VideoPlayer' classes in XNA 4, and hoped to make a game that works a little bit like how Myst does - with very active backgrounds, but no actual 3D graphics. (Technically, Myst 1 had static backgrounds, but maybe you get the idea) I threw together a small test game in XNA, with a pretty simple WMV included.

The problem I have is that it's not quite responsive enough. I'd like my system to be able to swap the current video in a millisecond, so that the player could click a contraption in the background and instantly see it move. Right now, when I press my trigger key that calls this code:

```
    private void cycleVideos()
    {
        videoIndex++;
        if (videoIndex == videos.Count)
        {
            videoIndex = 0;
        }
        activeVideo = videos[videoIndex];

        vp.Stop(); // Couldn't find a 'Seek(0)' method
        vp.Play(activeVideo);

    }

```

...it takes about a full second to re-seek the position it needs, and start playing again. In this example, I hadn't even encoded my video to the HD (1920x1080) resolution I had been planning on. I can understand if XNA's video system is really only meant for full cutscenes between missions or that sort of thing; I'm willing to use additional memory to have large parts of my videos cached, or even include a bit of a dynamic caching system so that things are loaded/unloaded over time (after all, this is the main visual of the game), but I'd like to hear if I have any decent options to accomplish this.

I'm also somewhat open to the idea of using a different engine or coding environment entirely.

EDIT: I've been doing some experimentation in my eagerness to solve this. I can definitely get some faster responsiveness by avoiding the 'stop()' calls, and by maintaining multiple instances of VideoPlayer. A paused video will resume much more quickly; and it's possible to play(), then pause() a video immediately (at the beginning of the program, in order to 'cache' it). It's not a full solution yet - I want to be able to seek back to the beginning of a video, and I still feel like there should be some possibility of that somewhere.

# Answer
> 1 votes
To seek you should use the `PlayPosition` property of `VideoPlayer` (http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.media.videoplayer.playposition%28v=xnagamestudio.31%29.aspx)

I think the best way to do this, if you want quick turnaround time, it to cache the `VideoPlayer` instances.

Another idea would be just to cache the textures for x seconds, while the `VideoPlayer` reloads the new file, then switch over to take the textures from the loaded one. To expand on this idea: you can make a new class `CachedVideo` which will be a "lightweight" wrapper over `Video` and `VideoPlayer`. Here, you will implement the `Update` and `Draw` loops in a 'producer-consumer' pattern, using a circular buffer:

* `Update` takes a texture and puts it into the buffer
* `Draw` takes one texture and draws it.

To allow a period of pre-buffering, you could specify a certain time amount to execute just the `Update` loop before actually executing the `Draw` call. This way, even if you need to loop the video, you'll already have something like 3-5 seconds of pre-buffering.

One problem still arises here is that the initial pre-buffering still takes a while. You could mitigate it by letting some sort of load screen to be shown in the meantime.

---
Tags: xna, video
---


# Question
Title: GL_EXT_shadow_samplers killing my shader
I have the following fragment shader for my scene

```
#extension GL_EXT_shadow_samplers : require
...
vec4 color = texture2D(uTextureUnit0, varTexCoord0);

if (colorTransformEnabled != 0) {
    vec3 transformedColor = colorTransform * color.rgb;
    color = vec4(transformedColor, color.a);
}
gl_FragColor = color;

```

this works like expected.

Now I add this line:

```
float shadow = shadow2DProjEXT(uShadowTexture, varShadowCoord);

```

and boom my shader does not produce any output at all. `GL_COMPILE_STATUS` and `GL_LINK_STATUS` do not return any error messages. Any idea where to go from here to debug this?

Edit:

I'm on iOS and GL\_EXT\_shadow\_samplers is supported.

Edit:

I forgot to check for error at some point. Now I get a `GL_INVALID_OPERATION` on `glDrawElements`. Any idea what could cause this problem? Since I do not get the error when I don't use the `shadow2D` functions.

Edit:

The following state change overview might help some more:

Where GL\_TEXTURE0+1 is the depth texture and GL\_TEXTURE0 is the objects texturea

Edit:

I found out that it produces the error as soon as the shader contains a call to shadow2DProj the invalid operation error is thrown. Although the shadow2DProj function is never called in the shader. And it still throws the error if shadow2DProj is called.

# Answer
> 1 votes
The problem was, that the texture was not correct mapped to the shader. There was a check for the type of texture before calling glUniform1iv that ignored the shadow map.

---
Tags: shaders, opengl-es2, shadow-mapping, fragment-shader
---


# Question
Title: Is there an easy way to add TMX Object Layer to a Scene in Andengine?
I have a TMX file with a MAP layer and Object layer (called decorations, with property type = "decorations"). Is there an easy way to add the whole layer to the scene with all objects? Or do I have to iterate through objects and add them one by one?

# Answer
After analyzing the TMX extension code, I am pretty sure there is no easy way. The extension doesn't implement objects layers as attachable to the scene, nor it read all information from the TMX file in the current version.
> 0 votes

---
Tags: andengine
---


# Question
Title: How should I choose a graphics card that's right for my needs?
I'm developing my own game using Ogre3D, and I'm want to implement things like SSAO, dynamic shadows, AI, physics, etc...and I know my current card is barely gonna be able to handle it.

So my question is, how do I find out what I'll need in a graphics card to support the features I want to implement?

# Answer
Say, for the sake of example, that you were pondering your GT8500 and whether you need to replace it. Here is the only relevant part of your card's spec:

> API Support
>
> * Complete DirectX support, including Microsoft DirectX 10 Shader Model 4.0
> * Full OpenGL® support, including OpenGL 2.0

If you intend to use features beyond these in your game, you need a new card. But you might want to keep the old hardware handy for testing purposes.
> 1 votes

---
Tags: graphics, nvidia, amd
---


# Question
Title: MonoGame Linux Mouse.SetPosition doesn't work!
Having a really weird issue, it seems that no matter what I do I cannot get the Mouse to lock to the center of the screen in MonoGame. I triple checked all the possible noob mistakes, and Mouse.SetPosition does get called. Weirder still, setting Game.IsMouseVisible to false does nothing as well.

```
        public override void Update(GameTime gt)
        {
            _lastmousestate = _mousestate;
            _mousestate = Mouse.GetState();
            if(LockMouse)
                Mouse.SetPosition(100,100);
            Point distance = new Point(_mousestate.X - _lastmousestate.X, _mousestate.Y - _lastmousestate.Y);
            MouseEntity.Position = new Point(MouseEntity.Position.X - distance.X, MouseEntity.Position.Y - distance.Y);
        }

```

I'm using Linux Mint 64-bit with Cinnamon.

# Answer
http://monogame.codeplex.com/discussions/390201

In this thread the user is struggling with getting the mouse-position(Mouse.SetPosition) to work. Unfortunately it is a bug within MonoGame so it is going to have to take some internal editing. Please look at the code/instructions he has posted within the thread so you can solve your error. It seems like this error is Linux specific only.

I could not find anything on your `IsMouseVisible = false` not working. Perhaps if you make the following adjustments in the linked thread above, it might work.

EDIT:

The fixes are within two files: OpenTKGameWindow.cs and Mouse.cs

I would submit a bug report to OpenTK, however I am not sure if your bug report will be acknowledged. It's last release was on 2010-Oct-06. It seems like it is being neglected.
> 0 votes

---
Tags: xna, c#, monogame, mouse
---


# Question
Title: Repeating Sound with Timer in Actionscript 3
I'm working on a Flash game and am trying to figure out how to repeat a sound periodically every 17 seconds. Instead, of having the sound repeat once the .mp3, .wav, finishes.

The problem I'm running into is the sound is repeating itself after the song finishes, and the timer isn't doing anything. I put the timer in the initTitle area because I'm working on my main menu, and then I initialize the sound, and read if the sound finishes. How can I get it so that sound repeats every 17 seconds?

```
    public function initTitle():void
    {
        initSoundThemeSong();
        initTitleWhooshSound();

        drawTitleBG();
        drawTitleLogo();
        drawTitleBGStars();
        drawTitleStart();

        titleWhooshTimer = new Timer ( 17000 );
        titleWhooshTimer.addEventListener( TimerEvent.TIMER, onTitleWhooshFinished );
        titleTimer.start();
    }

    public function initTitleWhooshSound():void
    {
        titleWhoosh = new TitleSoundWhoosh();
        titleWhooshSoundChannel = titleWhoosh.play();
        titleWhooshSoundChannel.addEventListener( Event.SOUND_COMPLETE,
                                                  onTitleWhooshFinished );
    }

    public function onTitleWhooshFinished( event:Event ):void
    {
        titleWhooshSoundChannel = titleWhoosh.play();
        titleWhooshSoundChannel.addEventListener( Event.SOUND_COMPLETE,
                                                  onTitleWhooshFinished );
    }

```

Thanks! :)

# Answer
Computers are incredibly smart, and incredibly dumb; because they do exactly what you tell them to. For instance, *you're telling it to play the sound when it finishes*. =p

```
titleWhooshSoundChannel.addEventListener( Event.SOUND_COMPLETE,
                                                  onTitleWhooshFinished );

```

You have that line in several places in your code, but you should only need it on the timer. Since that method has a 'play()' command in it, it will do just that. I'm wondering if this will work correctly without an event listener to note when the sound is fully downloaded, too.
> 1 votes

---
Tags: actionscript-3, sound, timer
---


# Question
Title: Screen or World Coordinates to tile Coordinates
I have Plane made of tiles in opengl. I start drawing them at (0, 0, -20) after that i do my translations so that the view is rotated somewhat similar to an isometric (kind of) perspective.

I'd now like to know, how many tiles are visible in each direction. So what i need to know basicly is, which coordinates (int the "before translation" - space) are now visible in the translated view.

The "tiles" before the translations" (for example in x direction there are 14 tiles visible):

And after the translations ( now there are 28 tiles visible in "old" x direction):

I tried to get the visible area via gluUnproject with no success.

**EDIT:** I already asked this question when i was trying to build the exact same thing in 2D and i got a good answer:

Calculating the number of tiles shown on an isometric map

maybe this helps to describe my problem further.

# Answer
> 2 votes
The problem is actually much simpler than you make it sound. Suppose `wx`, `wy` are your "world" coordinates -- that is, the native coordinates of your tiles. In order to transform that into the screen coordinates `sx`, `sy`, you apply some matrix transform. This can be written as: `(sx, sy) = (dx, dy) + M * (wx, wy)`. You already have that equation somewhere in your program.

Now all you need to do is to invert it:

```
(wx, wy) = Inverse[M] * (sx-dx, sy-dy)

```

where the inverse for a square 2x2 matrix can be found for example on Wikipedia.

*That's it.* Now you can find which tile corresponds to a particular point within your window. For example in the top-left corner you have `(sx, sy) = (0, 0)`. Plug those values into the formula above and you'll have the tile which sits in the top-left corner. Repeat for all other corners. Note that the complexity of this method is O(1), whereas the frustum culling will be at least O(n^2).

# Answer
> 0 votes
Although it doesn't seem like it, frustum culling is the answer here.

What you want to do is get a frustum from your view. This is determined by the screen width and height, the field of view angle and the near and far plane. Convert your view frustum to world space or your tiles to view space, depending on which is faster.

For every tile, determine if they are inside or outside the frustum. This is really simple, because a frustum is nothing more than 6 planes, so you can check a point against each of these planes. However, because your tiles are larger than a point, you'll probably have to do a check against an axis-aligned bounding box (AABB).

The frustum with AABB checks are explained here: http://zach.in.tu-clausthal.de/teaching/cg\_literatur/lighthouse3d\_view\_frustum\_culling/index.html

**EDIT**

Let's say you have a large array of tiles: 50 x 50.

Here's what you would do in pseudo-code:

```
std::vector<Tile*> tile_render;

Frustum& frustum_camera = m_Camera.GetFrustum();

for (int tile_y = 0; tile_y < 50; ++tile_y)
{
    for (int tile_x = 0; tile_x < 50; ++tile_x)
    {
        if (m_TileMap[(tile_y * 50) + tile_x].IsInside(frustum_camera))
        {
            tile_render.push_back(&m_TileMap[(tile_y * 50) + tile_x]);
        }
    }
}

```

Now you have a list of tiles that you can render.

The advantage of this technique is that when you have a very *very* large array of tiles you can chunk it up. For example, if you're dealing with 5000 x 5000 tiles, you can make 25 chunks of 1000 x 1000 tiles. First you check if the chunk is inside the frustum, and if it is, you add its valid tiles to the render list.

---
Tags: opengl, 3d, lwjgl, perspective
---


# Question
Title: How to animate a flip of a card in Cocos2d?
I am working on a card game and would like to ask if someone could advice me how to implement a flip of a card in Cocos2D?

# Answer
> 2 votes
Flip animation in cocos2d-android-1 like that...

```
CCSprite sprite=CCSprite.sprite("icon.png");
CCIntervalAction a = (CCIntervalAction)CCOrbitCamera.action(2, 1, 0, 0, 360, 0, 0);
addChild(sprite,1);
sprite.runAction(CCRepeatForever.action(a));

```

# Answer
> 0 votes
ios objective-c version:

```
CGSize winSize = [CCDirector sharedDirector].winSize;
CCSprite *player = [CCSprite spriteWithFile:@"Games1.png"];

player.position = ccp(player.contentSize.width/2, winSize.height/2);

CCActionInterval *a = [CCOrbitCamera actionWithDuration:2 radius:1 deltaRadius:0 angleZ:0 deltaAngleZ:360 angleX:0 deltaAngleX:0];
[self addChild:player];
[player runAction:[CCRepeatForever actionWithAction:a]];

```

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


# Question
Title: Where to put common System functionality in Entity-System Design?
I am working on an Entity System design based largely off of Adam Martin's design and Ray Wenderlich's Objective-C Implementation.

I am working on the AI system using a state machine with a System for each state. However, many of these systems share a lot of functionality, for example:

```
-(NSArray*)findEnemiesOfEntity:(Entity*)entity withinRange:(float)range {
    // Get all entities with a Team component
    // Narrow down entities to those on opposing team
    // For those that have a Position component:
    //     Get their position
    //     If their position is within range:
    //         Add to array of return values
    // Return array of return values
}

```

Obviously this functionality could be used in many ways; for example, the AIDefendSystem could use it to know if it is safe to move to the Attack State and the AIAttackSystem could use it to know when to return to a Defensive State.

So my question is this: **where does a function like the one above go in the design?**

Things I have thought of so far:

* A copy in each system: this seems quite redundant and hard to maintain. Perhaps because other design approaches view this as a code smell, I can't quite bring myself to do it.
* Inheritance hierarchy for systems: the common OOP solution to the problem of keeping a copy in each system. This also seems like bad design as it will encounter the same sorts of inheritance problems ES was supposed to solve (e.g. what happens when a non-AI system needs to know how many enemies are within a given range).
* A separate helper class with all these functions: to continue the database metaphor that Adam uses, I would interpret this as the "view" functionality in mysql. The downside to this would be a giant class full of seemingly unrelated helper functions
* The above approach with a single class per functionality: solves the giant class problem but creates either a singleton nightmare or dependency injection nightmare.
* Create another system with the functionality: this is the answer that "sounds" right, but I have no idea how it would work.

Let me know if I can provide any further detail or clarification. Thanks in advance!

# Answer
For my system I use an `EntityDirector` class. This takes care of common entity tasks, like tracking available entity IDs, reusing removed entities to save allocations, creating/deleting entities, adding/removing entity attributes and so on.

However, there are more specialized classes for different tasks. There's a `SpatialEntity` manager that has functionality like finding entities within an AABB, within a range of a specific point and other functionality having to do with location.

Then there's a `ThreatEntity` manager that knows the relationships between entity types. It can be queried for the threats between two entities. There are also functions that utilize the `SpatialEntity` manager to find all entities that are a threat to an entity.

Basically what I'm saying is, it's up to you. Split out the functionality into basic/simple logical classes. Then combine the simple functionality into more complex functions.

Where to place the more complex functionality depends on what's going to use it and how it's going to be used. This could be as simple as a large `EntityUtilities` class that contains and combines all the functions you want for your entities.

You can create a filter system for these functions. Where each simple function has a filter that describes the required components for an entity to be queried. For the more complex functions, these filters are combined to filter all the entities that don't have each of the required components to be passed into the functions. This would likely be something like a `long`, with a bit for each required component.
> 2 votes

---
Tags: architecture, entity-system, objective-c, design-patterns
---


title: Damage indicator screen overlay

text:
# Question
Title: Damage indicator screen overlay
I want to make something already done by a lot of games , which is when I am taking so much hits from enemy red screen drawn like the following , using XNA 4.0:

after it's drawn and I am still alive I want to be removed slightly as in the call of duty !!!

# Answer
> 3 votes
Since I am not familiar with shaders at all - I recommend this approach:

Create a texture in your favorite editor whether it be GIMP or Photoshop. Leave some sort of radial transparency in the center of the image so the player can actually see what he/she is doing amidst the red bordering the edges of the screen. Add that image to your XNA project, and scale it to fit the screen(or your players HUD - however you want to do it). When you get hit or get fall damage you simply display the image.

If you want to get fancy I would suggest using an alpha value to fade the image in based on the amount of damage you are taking. You should also have some sort of cool down factor so the image wont stay on the screen for long. Let us assume your player gets hit with a weapon that causes about 20% damage. Well you should "fade in" that texture's alpha to your desired X value based on the weapon that just hit them. You would then start the cool-down timer which fades the image away at your desired Y amount. The timer will reset itself again if the player gets hit. You may want to add some sort of delay on this timer.

---
Tags: xna, xna-4.0, graphics, graphics-programming, graphic-effects
---


# Question
Title: How do I approximate the result of battle between two armies with known strengths?
I need a simple algorithm to calculate the outcome of two differently sized armies battling.

Each army has 1-100 troops and every troop is the same value on the battlefield. The troops do not have individual stats. The only parameter on each army is the number of troops. For example: A with 57 troops battles B with 89 troops. Who wins?

Randomness can be a factor: For example, there could be a 50% chance that team A's total is subtracted by half of team B's total. Here's what I have so far (in a variation of BASIC):

```
lbl 1
If A>B goto2
If A<(or equal to)B goto3
lbl 2
50% chance B-((A-B)/2)→B
50% chance A-(B/2)→A
goto4
lbl 3
50% chance A-((B-A-/2)→A
50% chance B-(A/2)→B
goto4
lbl 4
If A=0:stop
If B=0:stop
goto1

```

So this system repeats until one of the armies reaches 0 troops.

The problem is, the battles go too fast. The battle is done almost instantly sometimes. Is there a better algorithm?

# Answer
> 5 votes
The simplest solution is to simply use the ratio of the two forces as the probability of success/defeat. If you want a method that does not happen instantly, simply implement this method one unit at a time, with a variable speed and output threshold.

For example, 57 vs 89 troops would mean that, for the first step, one side has a chance of 57/146 (39%) to lower the other side by 1, the other has an 89/146 (61%) chance to lower the first side by 1. Each step proceeds until one side wins.

The speed can be variable, the number of units lost per step can be variable, and it's a fairly safe way of showing a realistic simulation.

# Answer
> 1 votes
When you think about soldiers sitting in trenches firing at each other with a constant fire rate, you could model it by giving each soldier an x% chance to hit and eliminate one enemy soldier per shot, and repeat until one army is defeated.

```
double kill_chance = 0.05; // 5% chance to kill an enemy per round
int troops_A = 57; // starting strength of army A
int troops_B = 89; // starting strength of army B

// combat loop
while (troops_A > 0 && troops_B > 0) {
    int losses_A = 0;
    int losses_B = 0;
    // army A fires
    for (int i = 0; i < troops_A; i++) {
         if (random() < kill_chance) losses_B++;
    }
    // army B fires
    for (int i = 0; i < troops_B; i++) {
         if (random() < kill_chance) losses_A++;
    }
    // remove casualties
    troops_A -= losses_A;
    troops_B -= losses_B;
    // here would be a good place to report the combat progress to the player
}
// make sure no army ends up with a negative amount of soldiers
if (troops_A < 0) troops_A = 0;
if (troops_B < 0) troops_B = 0;

```

The function `random()` in this example is expected to returns pseudorandom floating-point values equally distributed between 0.0 and 1.0.

Keep in mind that this algorithm allows for the battle ending in a draw with both armies losing all their soldiers. This would be equivalent to the last two soldiers shooting each other and then bleeding to death. When you don't want this to happen, you could decrement the enemy troop count in the fire loop of each army instead of decimating them afterwards. This, however, would give an advantage to the army which fires first.

Yeah, war is hell.

# Answer
> 0 votes
It's very simple example and has nothing to do with my comments (example in js) You could spice it by giving random advantage to one side or another + other rules.

```
var red = 50;
var blue = 100;

while ( ( red != 0 ) && ( blue != 0 ) ) {
   var result =  Math.floor((Math.random()*(red+blue))+1);
    if ( red < result   ) {
        red--;
    } else {
        blue--;
    }
   document.write('red:'+red+' '+ ' blue:'+blue+"<br />");
}

```

# Answer
> 0 votes
I'm going to improve on the idea of soldiers shooting each other, and then simulating the battle. The fact that you dislike the high speed of the current simulation makes me assume that having simulation (as opposed to direct computation) is part of your goal.

## Method 1

The simulation is run in time steps. Each time step, each soldier has a probability of dying given by the formula `1 - (1-X)^(B/A)`, where X is a number between 0 and 1 (but much closer to zero), B is the number of living soldiers in the opposing army, and A is the number of living soldiers in that particular soldier's army. To be specific, X is the probability of dying when a single enemy soldier fires a single bullet towards you.

## Method 2

This simulation is also run in steps. Each step, one soldier is randomly chosen to be killed. Pick a random soldier from all of the soldiers. Then, figure out which team that random soldier is on. The *opposing* team receives the fatality.

If we were to just kill a random soldier, then the larger army will have a higher chance of having the fatality, which is the opposite of real life. By my method, a soldier on a smaller team has a higher probability of being killed.

For example, if Army X has 57 men and Army Y has 89 men, then there is a 61% chance that Army X will have the first fatality and a 39% chance that Army Y will have the first fatality.

---
Tags: game-design, algorithm
---


# Question
Title: Can you use a struct instead of an array to hold vertices in directx?
So instead of using an array to hold vertices information use a struct instead. Is this possible, does the Idirect3dvertexbuffer allow it?

# Answer
> 1 votes
Yes, you can. You can also use structs containing arrays, or arrays containing structs.

All D3D expects is a pointer to a block of data, formatted according to the specifications you provide it when you create the associated vertex declaration, and containing information of the appropriate type.

If your structures, or arrays, or whatnot provide that, then D3D will accept them regardless of the representation you chose for them in your code.

# Answer
> 0 votes
Technically, it's oblivious to whether you are using a struct or an array, it's just dealing with a pointer to a regular set of data. Structs and arrays are compiler constructs, and the DirectX logic is agnostic to the compiler that produced the data it's being fed - however I too am curious why you would use a struct - much larger chance you might get data organization messed up

---
Tags: c++, directx
---


title: Bright colors versus duller colors

text:
# Question
Title: Bright colors versus duller colors
I was talking to a friend the other day and we got onto the discussion about colors in videogames, relating to actual in-game graphics/art. He told me that even though it's easy to see things when everything's brightly colored, sometimes it's better to use dulled or faded colors, especially for things that you might see all the time (like walls or crates or rocks.)

The question I have is, does it matter too much if I have a lot of bright, lively colors for game graphics/art? Or should I tone it down to less lively, dull colors? Does it even matter too much, or can something like this only be evaluated on a game-by-game basis?

# Answer
It's much more complex than that. It's not the colors themselves that look attractive, it's the combination of colors, the contrast between them. In a picture only out of bright colors, there is a lack of contrast, same for a picture only consisting out of dull colors. In a picture out of dull colors bright spots will immediatly jump into the eye, this can be both distracting and guiding, depending on what elements it is used for. In the best case you use it to make the important game elements more appearant.

A general rule of thumb for games: **Use dull colors for backgrounds and bright colors for characters/gameplay elements.**

Note that not only Saturation produces contrast.
> 10 votes

# Answer
What you don't want to run into is so much visual clutter that you can't easily tell what is going on. Backgrounds should generally be more muted and foreground elements should generally be brighter and more lively. Granted, some games work with equally bright/muted elements all around *(Elder Scrolls, I'm looking at you -.-)*

Depending on implementation, this can be achieved through coloration or some other method (blurred focus for background elements, for example).

Even though it's a pixel art tutorial, Tsugumo has some good insight into this sort of thing: So You Want To Be A Pixle Artist?
> 3 votes

# Answer
I'd say it depends solely on what kind of game it is and what kind of feel are you trying to create.

Let's say you are creating a dark fantasy RPG targeted to older audience. You will definitely want to have lower contrasts, darker and dull colours. Fog, darkness. You will reserve bright colours for magic effects. Look at Planescape Torment!

When you are creating cute platformer for younger audience, you will want a lot of bright colours and a lot of contrast in the layer where the game happens and low contract in the background (and foreground) layer. You can even use bright and vivid colours for background, just avoid contrasts. Human eye is very sensitive to contrasts and edges. Check out games like Rayman or Worms. Plenty of colourful backgrounds.

And then of course when creating a realistic 3D game you want to recreate the real colours as closely as possible.

So yes, something like this can only be evaluated on a game-by-game basis.
> 2 votes

# Answer
It does matters and it entirely depends on your vision of your game. For a quick example, compare Diablo I vs. Torchlight. Games are essentially the same, but the color palette differs drastically.

Of course younger kids are more attracted to vivid colors and cartoonish figures, where's older generation (25+) have more mature tastes and might prefer grim / realistic sets.

EDIT: Closest match I could google up yet: Do bright colors appeal kids
> 1 votes

---
Tags: color, graphics-design
---


title: Help understanding Simplex Noise

text:
# Question
Title: Help understanding Simplex Noise
**Introduction**

This is less of a "how to" on using 2D simplex noise and more of a quest to understand what is happening both in the math and visually. I would rather not copy and paste the code I've found. I really would like to understand it.

I have done my homework on the subject and have read through Stefan Gustavson's paper and other sources many times. I feel like I understand about 70% of what my sources are saying, but when I try to manually follow my code loop through to check my understanding I either get hung up on what the variables represent or the math just doesn't add up.

I have begun to rename the variables in the code I've found in order to better understand what's going on. **If someone with some knowledge of what is actually happening can cross reference the original code (basically Gustavson's code) with my code that would be most excellent.** I'm not actually done with renaming the variables though, partly because I'm stuck.

**My Understanding**

Let's say I pass pixel (2, 3) into my noise function. At this point I'm working with a normal grid and my goal is to translate this normal grid into a simplex. This simplex is in the form of many triangles since we're working in 2D and supposedly this is better for various reasons.

To translate this point from the normal grid to the simplex grid, I must scale the point along the main diagonal line. After doing that, I apparently don't care about the decimals because I then Floor the results putting it back near the closest previous grid point.

Now I'm going to align the simplex cell to the normal grid by unskewing the simplex cell. Why I do all this work to get to the simplex cell, then undo it I'm pretty hazy on. Seriously, I think the best way for me to understand this is if someone could whiteboard out in steps what the heck is going on here. Super lost.

I didn't walk away empty handed though. I now have what I believe to be the distance between the original grid point I passed in and the simplex point I translated from that original grid point. Woo.

I think I'll stop here for now, just because I don't want this to turn into a huge wall of text. I'm pretty sure the rest of this will click once I understand the the beginning part.

**Weird Math**

Using the (2, 3) point from earlier, this is what I get by stepping through my own code on paper:

```
x = 2
y = 3

skewfactor = 1.830
unskewFactor = 1.479
unskewed_x = 1.520
unskewed_y = 2.520
simplexCell_i = 3
simplexCell_j = 4
x_distance0 = -1.520
y_distance0 = -1.520
i1 = 0
j1 = 1
x1 = -1.309
y1 = -2.309
x2 = -2.5207
y2 = -2.5207
ii = no idea why this isn't i2 or something like that. No idea what this is.
jj = same

```

Not sure if plotting on a graph would work, but I tried and it looks so bad. I used the original parameters (2, 3), simplexCell\_i & j, i1, j1, x1, y1, x2, and y2. Doesn't make any sense visually.

Not just visually, but mathematically as well. What's with (2, 3) returning negative numbers that go off the chart? What am I doing wrong here?

# Answer
I think it helps to compare it side-by-side with regular Perlin noise. As explained in the Gustavson paper, Perlin noise works by assigning pseudo-random values (gradient vectors) to each corner of a square grid and then doing some interpolation for points in the interior of a grid cell. So the first step in evaluating Perlin noise is to figure out which grid cell you're in. That's what the `floor` function is doing: all the values between 0 and 1 are in grid cell 0, between 1 and 2 are in grid cell 1, etc. along each axis. So in classic Perlin noise you'll see some code like

```
int i = int(floor(x));
int j = int(floor(y));

```

Once you know which grid cell you're in, the rest of the algorithm can proceed.

With simplex noise, as before, the first thing you've got to do is figure out which grid cell you're in. But it's a simplex grid now, which isn't related to the input x and y in such a simple way as the square grid. However, as Perlin noted, and as Gustavson shows in the picture on page 6, if you scale a square grid along its diagonal by just the right factor, the squashed grid cells now have a shape that can be made up of several simplices. (In 2D, for instance, the squashed square is a rhombus that can be made of 2 equilateral triangles. In higher dimensions you'd have more than 2 simplices in each grid cell, but it's the same idea.)

So this provides a way to bridge the gap between the Cartesian coordinate system and the simplex grid. First you figure out which grid cell you're in with respect to the squashed square grid; then you figure out which simplex you're in within that squashed square grid cell.

To figure out which cell of the squashed square grid you're in, you first execute a linear transformation to a coordinate system whose axes line up with the squashed grid. Perlin writes it something like:

```
float F2 = 0.5*(sqrt(3.0)-1.0);
float s = (xin+yin)*F2;
float xSquashed = x + s;
float ySquashed = y + s;

```

Here `xSquashed`, `ySquashed` are coordinates in the local space of the squashed grid. If you stare at this for a minute, you'll see it's equivalent to the matrix transformation:

```
[ xSquashed, ySquashed ] = [ xIn, yIn ] * [ 1+F2 F2   ]
                                          [ F2   1+F2 ]

```

So it's just a linear change of coordinates, although the matrix multiplication is written out in a way that makes that non-obvious.

Then calculating which grid cell you're in is, just like before, simply a `floor` call on those local coordinates. That gives you the grid cell index for one corner of the simplex. Some more fiddling with the coordinates determines which simplex you're in within the squashed grid cell, and from there you can figure out the grid cell indices for the other corners of the simplex.

Finally, why do you transform back to the regular, non-squashed coordinate system? It's because in the final stage of the algorithm, when you add together the contributions of all the corners, you want to be working with ordinary distance, not the pseudo-distance in the squashed space. That's so the noise interpolates cleanly and doesn't come out with a squashed appearance. Note that what you're transforming back to regular coordinates isn't the original input point, but the first corner of the simplex. Once you've got that, you can find the locations of the other corners and proceed with the rest of the algorithm.

As before, this transformation is written in an odd-looking form but it's equivalent to the matrix transformation:

```
float G2 = (3.0 - sqrt(3.0))/6.0;
[ X0, Y0 ] = [ i, j ] * [ 1-G2 -G2   ]
                        [ -G2   1-G2 ]

```

If you calculate it out, you'll see that this matrix and the one mentioned above are inverses of each other.
> 11 votes

---
Tags: algorithm, maps, perlin-noise
---


# Question
Title: Java - Best Implementation KeyListener For Games
I am working on a game using only the swing and awt packages. Note I can only use the default Java libs. Meaning I have to use KeyListener. I have imported KeyListener properly, however, it is still relatively buggy. Here is a snippet of my code.

p is for Player class, I am going to set x and y to private, however, this is for simplicity

```
public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;

    if(keys[KeyEvent.VK_W] || keys[KeyEvent.VK_UP]){
        p.y += 5;
    }

    if(keys[KeyEvent.VK_S] || keys[KeyEvent.VK_DOWN]){
        p.y -= 5;
    }

    if(keys[KeyEvent.VK_A] || keys[KeyEvent.VK_LEFT]){
        p.x += 5;
    }

    if(keys[KeyEvent.VK_D] || keys[KeyEvent.VK_RIGHT]){
        p.x -= 5;
    }
}

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}

public void keyTyped(KeyEvent e) {
}

```

Sadly this code has a lag to it. Of a second... Also, the motion is not a fluid... However, I don't want you to fix my code. Rather, what other methods are more clean? As well, I have worked with engines, they all seem to have an: isDown, PressedOnce, Released(However, I know how to implement this), ect.

# Answer
**Possible cause :** From your code, no visible sources of lag are present. The lag may come from the way they are accessed from the game loop thread. Dont forget, the variables have to be synchronized, or you have to use locks for your app to be thread safe.

The lag you experienced may be from the fact that you increment the *x* and *y* by 5 each. I am guessing that this makes them move by 5 pixels. Maybe if you change it to something like 2, you will see smoother graphics.

**Suggested format:** I suggest you try to implement something like the following for maximum efficiency and thread safety.

**Explanation :**

```
1. The InputManager class detects the input and stores them in local variables inside
the InputManager class itself.

2. At some point in the game loop, a method (Maybe getProcessedData()) is called that
is inside the InputManager class that processes the data stored in it and returns.

3. The recieved information is used by the game loop.

4. Don't directly modify the original flags(The ones in the game loop) as is may lead
to unstability.

```

**Additional :** Another possible source of lag may be that you are processing heavily in the game loop. Try moving heavier processes to new threads.

**Experience :** Designing a multi-threaded platformer using swing. Pretty similar to yours.
> 6 votes

# Answer
Your problem is that you are doing the update logic in `keyPressed()` method.

When you press a key, AWT will call this method once. After a delay (typically 250-1000 milliseconds) it starts calling this method again repeatedly with a smaller delay (typically 30-400 milliseconds). When the key is released, this repetition stops and `keyReleased()` method is called. In Windows these delays can be controlled from Keyboard properties inside Control Panel. If you hold down multiple keys simultaneously, the repetition events are sent only for one of the keys.

What you should do is to update only the state of the keys in the event handlers and process the movement outside those. With your `keys` array you are already almost there. Change your code to the following:

```
public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;
}

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}

public void keyTyped(KeyEvent e) {
}

public void update() {
    if(keys[KeyEvent.VK_W] || keys[KeyEvent.VK_UP]){
        p.y += 5;
    }

    if(keys[KeyEvent.VK_S] || keys[KeyEvent.VK_DOWN]){
        p.y -= 5;
    }

    if(keys[KeyEvent.VK_A] || keys[KeyEvent.VK_LEFT]){
        p.x += 5;
    }

    if(keys[KeyEvent.VK_D] || keys[KeyEvent.VK_RIGHT]){
        p.x -= 5;
    }
}

```

You need to call `update()` repeatedly, once per "frame". Where you should call this method depends on the rest of your code, but typically it's one of:

* A busy loop where you also trigger rendering
* Another thread (in which case you need proper synchronization)
* Paint method, if you let AWT to handle your game loop

You also need to consider timing so that either this method is called with a constant rate or the implementation of update can handle variable time steps. (http://gafferongames.com/game-physics/fix-your-timestep/)
> 3 votes

# Answer
I take it that you are keeping an array or an ArrayList, maybe of booleans, that records key states and have some key listeners that modify that. It's hard to see what else, given the limited snippet of code.

Just make your game loop, thread, etc implement the KeyListener interface, unless that is that what you are doing. I think the motion being fluid or not would depend on the rate of increment and how fast the program responded to the input, etc. For best results you would want the player to keep moving if the key is still pressed, and only stop if the key is released. Instead of moving on press/release, you could have a boolean indicating whether the player is moving that is set to true when -key pressed- and false when -key released- and the movement is handled elsewhere as long as key pressed is true. Come to think of it, that would probably help my pong game a bit...
> 1 votes

---
Tags: java, game-mechanics, keyboard, controllers, swing
---


# Question
Title: How can I have multiple layers in my map array?
How do I load Levels in my game, as in Layer 1 would be Objects, Layer 2 would be Characters and so on. I only need 3 layers, and they will all be put on top of each other. i.e having a flower with a transparent background to be put on grass or dirt on the layer below.I would like to Read From the same file too. How would i go about doing this? Any help would be appreciated.

I load the map from a level file which are just numbers corresponding to a tile in the tilesheet.

Here is the level file

```
[Layer1]
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
[Layer2]
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
[Layer3]
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

```

And here is the code that interprets it

```
void LoadMap(const char *filename, std::vector< std::vector <int> > &map)
{
    std::ifstream openfile(filename);
    if(openfile.is_open())
    {
        std::string line, value;
        int space;

        while(!openfile.eof())
        {
            std::getline(openfile, line);

            if(line.find("[TileSet]") != std::string::npos)
            {
                state = TileSet;
                continue;
            }
            else if (line.find("[Layer1]") != std::string::npos)
            {
                state = Map;
                continue;
            }

            switch(state)
            {
            case TileSet:
                if(line.length() > 0)
                    tileSet = al_load_bitmap(line.c_str());
                break;
            case Map:

                std::stringstream str(line);
                std::vector<int> tempVector;

                while(!str.eof())
                {
                    std::getline(str, value, ' ');
                    if(value.length() > 0)
                                 tempVector.push_back(atoi(value.c_str()));
                }
                map.push_back(tempVector);
                break;
            }
        }
    }
    else
    {
  }
  }

```

and this is how it draws the map. Also the tile sheet is 1280 by 1280 and the tilesizeX and tilesizeY is 64

```
void DrawMap(std::vector <std::vector <int> > map)
{
    int mapRowCount = map.size();

    for(int i, j = 0; i < mapRowCount; i ++)
    {
        int mapColCount = map[i].size();

        for (int j = 0; j < mapColCount; ++j)
        {
              int tilesetIndex = map[i][j];
              int tilesetRow = floor(tilesetIndex / TILESET_COLCOUNT);
              int tilesetCol = tilesetIndex % TILESET_COLCOUNT;
              al_draw_bitmap_region(tileSet, tilesetCol * TileSizeX, tilesetRow * TileSizeY, TileSizeX, TileSizeY, j * TileSizeX, i * TileSizeX, NULL);
        }
    }
}

```

EDIT: https://i.stack.imgur.com/GWQSq.jpg

# Answer
> 1 votes
After dealing with similar project over the last 2 years (as an amateur game developper) I had to face the fact that this method was totally outdated, and somehow more complicated in time than others.

I would advice you reviewing totally the format of your map and the way you handle layers. A good example is the Tile Map Format **.TMX**(Tmx Map Format documentation here) which can be used with the free and open-sourced **Tiled** editor(Tiled website).

I find it to be really flexible and convenient. Most of the platformers and RPG games I developp use this file format. Moreover, several code examples exist on the internet for almost every language. I even use it on a professionnal JavaScript project.

I know it doesn't really answers your question but it is a good alternative in my opinion.

# Answer
> 0 votes
I didn't watch the code, but if I understood it well, you'd like to use layers on a similar way as they are used in platformers, isn't it?

In that case, I'd suggest you to make an array for every layer and make some cross-effect between them. Here's an example (just parts):

```
#define x 30
#define y 30

int arr1[x][y];
int arr2[x][y];
int arr3[x][y];

Player player; //makes obecjt "player" belongs to class "Player"
Wall invisible_wall; //makes obecjt "invisible_wall" belongs to class "Wall"

player.posX = 10;
player.posY = 20;
player.layer = arr1; //maybe it's wrong, don't deal with it: the matter is that you may do a property that tells the layer the pbject lays on

invisible_wall.X = 10;
invisible_wall.Y = 20;
invisible_wall.layer = arr1; //maybe it's wrong, don't deal with it: the matter is that you may do a property that tells the layer the pbject lays on

if (player.layer == invisible_wall.layer)
{
stop player; //it's also wrong but you may add here that stops player moving
} else {
let player move; //it's also wrong but you may add here that lets player moving
}

```

This is not a proper code, but I hope I could get the logic I try to tell.

Also, it may be a wrong idea, but hopefully, it may help.

PS.: Byte56 was right: don't use layers if they are not necessary!

# Answer
> 0 votes
A solution to your problem would be that within your map class you create 3 std::vector\> each the same size representing each a layer of the map. Then within your loadmap function every time yiu encounter the appropriate layer you push back the integers that represent tiles. Esentially, you have the basis for the system you want, you just need a cotainer for each layer. Then when it comes to rendering, within the nested for loop render the appropriate image for the layers in order from bottom to top. Or you can use a priority map and render in order of priority. If you need it i can always post a simplified snippet of code later.

---
Tags: c++, allegro
---


# Question
Title: Is it acceptable to have a global singleton engine class, in an entity component model?
I am in the process of writing an entity component model game engine, and I wanted to ask about the best way to lay out the code. I have run into an issue that I know will quickly cause me to run into more problems, down the road. In short, I currently have a render component, that I attach to the entity class. The problem is, I need the render component to signal the render engine, and add itself to it.

I thought about creating a singleton for the render system, but I quickly realized that was a bad road, and sooner or later, I would be creating singletons for just about everything (Ex, physics for the physics component). What I am currently thinking of doing is creating the base engine class as my only singleton. The engine class is responsible for initializing all of the systems available, such as the graphics and file systems, storing references to them, calling the game loops update method, and keeping track of all the entities in the game. If I did that, then my components or any other part of the code could easily reference the important systems they need to deal with via a simple `Engine.MySystem`. In the case of my render component, `Engine.Graphics3D.addModel()`.

I am wondering is if this is an acceptable way of doing things, or not. If not, what would be better? I could, in theory, pass a reference to the GFX system to the render component, but that seems like a really bad idea. I feel like this is a nice middle ground between the two options.

# Answer
> 5 votes
No, I don't think you should do it this way. All you're doing here is *hiding* the dependencies and design flaws that appear to necessitate the singleton in the first place. In some ways, your suggested engine singleton is worse.

In any context, in any code, you can always replace a singleton with explicitly dependency injection (that is, passing a instance of the would-be singleton as a parameter) and plumbing that instance through the layers of your API. When you do that, the more layers you have to plumb the instance through, the more flawed your current design is for handling the dependency relationship in question.

Here's the crux of your design flaw:

> In short, I currently have a render component that I attach to the entity class. The problem is, *I need the render component to signal the render engine and add its self to it*.

(Emphasis mine.)

This implies that you can directly create a render component without a renderer itself. However, that fact doesn't actually gel with the architecture of the rest of your code, since you are having to go and look up some ubiquitous renderer instance and register the component with it. Invert that relationship, and have the renderer be the interface through which you create render components. That is, instead of what you have now, which looks like

```
RenderComponent c; // secretly talks to renderer, hiding a dependency

```

implement something like

```
RenderComponent c = someRenderer.CreateComponent();

```

This makes the relationship between those two interfaces more explicit and clear to the consumer of the code, and avoids your need for a singleton. Obviously the factory interface that products entities will need a reference to this "`someRenderer`," (in case creating a new entity would require creating a rendering component) but you can just pass that explicitly to the entity factory as well:

```
struct EntityFactory {
  EntityFactory (Renderer * renderer, /* other parameters */);
};

```

Here, you are only passing the renderer itself once. That's hardly egregious and it's much clearer and self-documenting. You may also need to pass other subsystem references to the entity factory, such as AI or physics systems, but that's okay too, because the entity factory *needs* those to do it's job.

Explicit is far superior to implicit.

# Answer
> 4 votes
Your entities do not need to know about a renderer, all they have to care about is sending a notification, "Hey! Someone please render me!" and be done with it.

Please consider the following design (NOTE: heavily simplified):

When the GraphicsSystem is initialized it basically says to the EventManager to notify it whenever something wants a model rendered.

The Model in turn, tells the EventManager that it mesh should be rendered every frame. The GraphicsSystem is notified and adds the mesh in its internal render queue.

The GraphicsSystem does not render anything in its render queues until the Render method is called.

The advantages with this design are:

1. Scalable
2. Loose coupling between objects
3. Rendering can be placed in a separate thread without much hassle
4. Rendering can be optimized since you now have a batch of entities to render
5. Easily replace a rendering engine with a different one
6. No singletons
7. You can have multiple render queues.
8. You can remove the renderer completely and the code wont break, the components will simply not be rendered.

---
Tags: entity-component
---


title: How to store NPC movement data?

text:
# Question
Title: How to store NPC movement data?
In my 2D tile-based game, I have NPCs that move around on a fixed path. I am putting the information about the NPCs in a .plist file that is loaded on startup. The thing is, I'm not sure how to format the data specifying the path that the NPC moves on. What I was thinking was to have an `origin` property, a `horizontalMovement` property, and a `verticalMovement` property, so when the starts at its origin, then walks right the number of tiles specified by `horizontalMovement`, then walks the number of tiles down specified in `verticalMovement`, etc. However, this doesn't seem like the best approach. Is there a better way to store the movement data?

# Answer
It all depends on how flexible you want to be. I dont think the approach you suggested is bad, in fact its one of two main possibilities i would consider in your case:

* store a list of checkpoints that the NPC walks through (once it reaches the last checkpoint it goes back to the first and repeats). Once arriving at a checkpoint, the NPC will find the best path to the next checkpoint (using A\* algorithm for example). This has some advantages, like for example the map can change (obstacles can move around etc.) but also can break down if there is no path between a pair of checkpoints. It is also a bit more complex to code.

OR, as you said:

* store a list of fixed actions: 1) walk 3 tiles south, 2) walk 4 tiles east... etc. Something very similar to what you suggested. Simple and easy to code, but not very flexible. Thats not necessarilly a problem though.

Its up to you to decide what works for you the best. **There is nothing bad in trying something you made up yourself, in fact its better than just always looking up a "perfect" solution on the internet.**

Good luck!
> 1 votes

---
Tags: ios, tiles, objective-c, data-structure, npc
---


# Question
Title: Sharp DX Identity Matrix, Matrix.Forward vector pointing at negative Z
I'm trying to take a steady grip on Sharp DX. Already done some work like translating, scaling and rotating objects. Now i have to calculate the rotation matrix using only direction vector and arbitrary UP vector which is Unit Y vector (0,1,0). And this is where everything I know about Direct X graphics falls apart: I filled the Matrix.Forward with the normalized DIRECTION vector, and then crossed it with arbitrary UP (exactly this: DIR cross UP, not the other way), the resulting vector put in Matrix.Right property. Now if I put (0,1,0) in the Matrix.Up property, my model is facing the exact opposite direction to the expected direction (it faces backwards). Further investigation brought me to the fact that the Matrix.Identity matrix faces the NEGATIVE Z direction, which is weird to me as I thought that Identity would face positive X,Y,Z axes. Now I can overcome my problems by flipping any of the axes, but this clearly is not comforting to me, as there is something i must have missed in the meantime. So the ultimate question is: Why my Identity matrix points positive Y axis (good), positive X axis (nice, i expect this) and NEGATIVE Z (help!)

# Answer
> 1 votes
A cross product gives you the perpendicular line. Both the negative and the positive vector represent the same perpendicular line. You'll have to change your order of operations to get the positive vector. Eg. DIR cross UP and UP cross DIR will give the same perpendicular line but might change the sign of the vector. (It's too early to do matrix computations to show that :P)

---
Tags: c#, matrix, vector, sharpdx
---


title: How to make a Socially Conscious Game?

text:
# Question
Title: How to make a Socially Conscious Game?
I'm working on a 4x, turn-based space game. It's currently in the design phase. Because I'm the Director of Technology for Gamers Against Bigotry, I'd like it to be socially conscious. In other words: I want the game to have features that encourage socially aware gameplay.

I've had some ideas. The first is that some worlds will have aboriginal peoples. Second, there will be some smaller empires (much like City-States in Civ 5) that don't colonize more than one or two systems.

In a normal 4x game, there is absolutely no penalty for attacking these civilizations, or for destroying aboriginals (their might be expensive military costs, but that's it.)

One idea I had was to set up a council of Elder Races who could punish players who interfere with Aboriginal Cultures. I also thought about using Factions that have to be appeased, and these factions could interfere with the player's ability to procede (for example, Human Justice factions would strike if the player hurt aboriginal peoples. Environmental factions might strike or destroy buildings that hurt native fauna/flora.)

Finally, I thought about allowing the player to choose their sexual identity (Male, Female, Trans\*, etc).

Does anybody have any other ideas to make the game more socially conscious? Obviously, gameplay should still be fun. I just want the players to think about their actions in a greater social context.

# Answer
# Summary: Depict differing world-views and perspectives in a value-neutral, non-judgmental way

In order to deal with prejudices, biases, and bigotry, I would focus away from artificial "This is a minority in the galaxy. It's wrong to hurt them!" style methods. It's not that it's inappropriate, but that it would be ineffective at doing anything but "preaching to the choir". Instead, the root cause of prejudices is unfamiliarity with different perspectives. Showing multiple perspectives in a neutral light would be the most effective means of actual change.

The best reference for this would be Alpha Centauri. A Firaxis/Civilization sci-fi game. It plays much like its sister game, Civilization. However, the civilizations that oppose each other have distinct personalities, and the leaders have equally distinct personalities. These leaders are quoted for every "Great Project/Wonder" and "Tech" that is built/researched. These quotes, more than any other fiction I've read/experienced, have driven a brilliant means of insight into differing perspectives.

The industrialist is often quoted giving justifications for a focus on capitalism. The autocrat has a quote giving a logical justification for his government's oppression. It's not the focus of the game by any means (they are simply quotes you needn't ever read), yet they repeatedly offer different perspectives to the player **without judging**.

This, I think, is the key to moving beyond "lecturing/moralizing" and moving towards "enlightening". Offering non-judgmental windows into other world-views. By doing so, by being as neutral as possible, anyone who is more likely to identify with the traditionally villainous character(s) will not be off-put by authorial attempts to cast what the player sees as the most identifiable character in a negative, sometimes wholly demonized, light.

This means the common defensiveness that occurs, which is more or less a cognitive bias called the backfire effect, is not as strong, so the player remains more open to the experience. It is this openness that leads to a higher chance of real change in perspectives, which should be the ultimate goal in any "socially conscious" fiction.

I'm not technically suggesting that you should utilize "quotes" like Alpha Centauri. Rather, utilize the general methodology, that of ***non-judgmental depiction of differing world perspectives***. This, of course, works best when told in the fictional universe with a consideration for relatability given the culture of the viewers/players (e.g. sci-fi versions of current social ills such as prejudices against Islam and homosexuality).

Source: Is a Licensed Counselor with cultural-change-focused master's
> 9 votes

# Answer
I find the idea of making a socially conscious game interesting. However, remember that this is a game, so I'd recommend you make sure whatever changes you make to the game do not impact gameplay in a negative way that may bore or annoy your players.

In my opinion, you should pick one facet of social consciousness (ethnics, nationality, sexual orientation, environmental issues) and focus on that one instead of trying to attack them all.

In general, I think you should allow players to perform the undesirable actions (for example, destroy an aboriginal society), but make them think that those actions have consequences, so the next time they play your game they'll think twice before doing that. For example, you can:

1. Make "diversity" an in-game statistic. This may either affect your science output, or the population happiness, or its cultural influence. Make sure you explain why those numbers are related.
2. Whenever you destroy a native civ, your troops lose morale, and get a temporary penalty in combat.

But it would definitely be best if not everything is negative when you do something undesirable. That way it doesn't become preachy. In other terms, it's better to give players a choice so they consciously avoid the undesirable behavior, than to simply punish it.

Take for instance, Anno 2070, where pollution and global warming are real problems that actually affect gameplay in both positive and negative ways (more pollution generating buildings give a boost to productivity, but will seriously affect the late-game. While greener buildings are not that productive, but will avoid problems in the long run). You may find some interesting ideas in there.

There's also another flash based game, Sweatshop. You may want to check it for other interesting ideas.

Other games are just based on delicate subjects to inspire discussion. For example Smuggle Truck is an awesome game, based on illegal immigration.
> 2 votes

# Answer
I don't think that your idea of having interest groups which punish the player for discriminating minorities sends the right message. It says "you need to protect these minorities, because someone else says so". The effect will be that the player will hate these interest groups because they limit their freedom. And when you make these interest groups use violence when their demands aren't met, you put them on the morally wrong side and give the player even more reason to disagree with their stance.

The message you want to say is **"You need to protect these minorities, because it is beneficial for everyone"**. Allow the player to trade with these factions, and make sure that it gives them an advantage. Reward the player for maintaining a good relation to them for a prolonged time. Make sure that destroying these factions gives little or no benefit.

Regarding giving the player the choice to select the sexual identity of their character: Will it have any notable effect on gameplay? When its a choice which is actually meaningless, you shouldn't do this, as it would feel tagged-on. Also, why do you force the player to choose?

A good example how to deal with sexual identity is, in my opinion, Mass Effect. The player character is able to engage in heterosexual, homosexual and xenosexual relations. The player can also play their character asexual, when they want to. But the player is not forced to clearly define the orientation of their character as they can engage in different relations over the course of the trilogy. An exceptionally good treatment of homosexuality is, in my opinion, the character Steve Cortez in ME3. He is an openly gay character who mourns the loss of his husband. Two men being married is accepted as perfectly normal by the game world (even by his colleague James Vega, who is otherwise portrayed as a simple-minded brute macho-man and would certainly also discriminate gays when he would be born in the 20th century). His suffering is portrayed very seriously and without any prejudices that gays wouldn't love each other as much as heterosexual couples. The portrail of the character himself is also far away from any camp-gay stereotypes. The player can help Cortez to overcome his loss, and when they play a male character, they can afterwards choose if they want to engage in a romantic relationship with him or just want to be friends. This again plays against the prejudice that gays would only have interest in other men when it's sexual and that men can't be emotionally close to homosexual men without being homosexual themself.
> 1 votes

# Answer
First of all, stop thinking in Human terms. If the player can pick alien race they can have 1 sex or more than 2 sexes!

You can also mix races in cities/on planets. You can create tension between races that will have negative impacts. You can create societies where civics like "multi-species society" positively boost culture or science.

Add bonuses to aboriginal races. Protection or peaceful incorporation of the aboriginal race should provide significat boost. You can make "first contact" rules for aboriginals and your planetary council can penalize players or even wage wars against those who break them. Let AI players break them and give the player a peacekeeping mission from the council that will provide some reward.

And watch Star Trek: TOS, that will give you plenty of ideas.
> 0 votes

---
Tags: game-design, strategy
---


title: GLSL Shaders-> How to manage?

text:
# Question
Title: GLSL Shaders-> How to manage?
As your game get's bigger and bigger, you will use more and more different shader effects. Let's take an easy example:

I have clouds in my voxel-based world, and I want to give it a blue-ish tint with a shader. Do I create a new shader, disable the default shader, enable the cloud-shader, draw the cloud, disable the cloud shader and enable the default one again?

If your game starts to get huge, how on earth can you use 300 shader effects enabled for 1 voxel and disabled for the other?

I know the question may sound strange, but it really makes me think.

I now have a Vertex- and Fragmentshader, for the matrix calculations, and basic lighting. If I want to add a shading-effect for for example water blocks, what to do?

I hope someone can help me with this mystery.

# Answer
This is solved in diffrent ways, some solve it by using #ifdefs, some solve it by branching And some solve it by having input values that updates per every object so you store an overall painting scheeme for the defualt shader.

and when it comes to scale of the game, it´s actualy no way around this. You will need more shaders for diffrent materials and diffrent objects. I Usualy go with the "per material" shaders. which means that i have some common vertex shaders that i can plugin depending on what you are doing with the vertex. and then you have a specific material shader, like wood, metal, stone and water. i have found this to be quite efficent. you may endup with diffrent customshaders but thats just okay!
> 2 votes

---
Tags: opengl, shaders, glsl, vertex
---