# Question
Title: Monogame/Android: Using content from PCL
I'm quite new to Monogame and PCL, but I hope someone can help me with my question.

I have a Monogame/Android project with references a PCL which targets .NET 4.5, iOS and Android. The PCL has content files suchs as SpriteFont and Texture2D. They are set to "Content", "Always copy" and are .xnb files. The problem is when I start my Android game I get a "asset not found" exception for the content in the PCL. When I launch my Windows game it works all fine.

To begin with, can I have content files in a PCL and is that good practice?

# Answer
> 1 votes
That's a good question. Unfortunately, I haven't got an ideal solution, but I do have a similar setup to you with a PCL and an Android project. As you can see, I have the content in the PCL set to "Content", "Copy if newer".

In the Android project I have added the same files under the Asset/Content folder as **links** to the original files and set their properties to "AndroidAsset". It works just fine, but it does mean I have to keep add content to both projects which is slightly annoying.

I'd be interested to know if a better solution to this problem comes up.

---
Tags: xna, xna-4.0, monogame, .net
---


# Question
Title: How to know the relative facing angles between two players?
I want a grappling system similar to Tekken, in which different grapples animations are performed depending on which side of the opponent the player performing the grapple is facing. For example, facing the opponent face to face would be different when he is facing the opponent's back or even facing the opponent from the side.

Overall I've seen three animations performed using the same buttons depending upon the side the player is facing the opponent. But I've no idea how to achieve this.

How can I tell if a player is facing the front, side or back of another player?

# Answer
If you know which direction the characters are facing, you calculate the dot product of those directions. If the characters only move on the ground plane it is pretty staightforward to decide which side are you on. If the dot product is 0 then you face exactly the side of the opponent. Then you check for some interval against zero and decide if you are on the side or not (so that you can attack from the side even if you are not *exactly* on the side). If the dot product is positive then you are behind, if negative you are in front. Calculate the dot product by multiplying the facing vectors' of the characters components against each other then sum them up, like:

```
vec1 = (a,b,c)
vec2 = (x,y,z)
dot(vec1,vec2) = a*x+b*y+c*z

```
> 1 votes

---
Tags: unity, vector, angles
---


# Question
Title: What are the correct angles in the Top-down perspective?
In the following picture it says that in the Top-down perspective the angles are 90°, but if it would be 90° then you shouldn't see the front of the building and the roof at the same time...

So what are the correct angles to get such an perspective?

# Answer
The picture you posted seems to be seen from a 45° angle. This perspective is sometimes informally called bird's-flight view. More formally, it is usually referred to as orthogonal, dimetric projection. Orthogonal means that all the world-axis are all parallel to a screen-axis (world-x is parallel to screen-x, world-y and world-z are parallel to screen-y). Dimetric means that two axis (y and z) are shortened by an equal amount, but the 3rd axis (x) isn't.

Dimetric projection does not use pespective shortening. That means objects far away from the viewer have the same size as those close to it. This makes the implementation of a 2d graphic engine much easier, because it needs no scaling.
> 2 votes

---
Tags: 2d, mathematics, camera, perspective
---


# Question
Title: Problems implementing a 3rd person static camera in Unity3d
I am building a space game that I would like to be controlled in third person.

Basically I would like the camera and the ship to remain tied together and remain the same distance from each other but for the camera to remain in the same position relative to the ship from the world perspective. This position of the camera relative to the ship can only be altered by mouse movement and not by ship movements.

Example of the functionality required would be:

* User can rotate the the ship on the x, y, z axis and the camera can observe these rotations
* User can position the camera on the right side of the ship using mouse movements and activate thrusters to observe the ship in the center of the screen and the background objects passing
* User can fly ship into an asteroid and observe rigidbody collider cause the ship to bounce back and start to rotate violently in a direction but the camera will remain stable and at a constant distance to the ship

Explanation from technical sense:

* The camera must remain at (0,0,-100) from the ship in world coordinates and this position only changed using mouse movement using local position
* Putting camera and ship in the same player object allows to control local coordinate to (0,0,-100) but from world perspective the positing of the camera to ship actually changes

Currently the main problem is that I can only either have the camera stuck in a constant position relative to the ship (cannot change perspective with mouse) OR I can change perspective with mouse but the rigitbody physics get applied to camera (if I hit an asteroid the camera rotates with the ship)

I also tried to use a dummy camera to track mouse movements and to just add it to the constant camera but when the ship rotated very quickly it wasn't very accurate.

Any suggestions for what I could use in order to get accurate response?

# Answer
> 1 votes
I think that you need is this:

```
//Calculate the vector between the camera and the ship
Vector3 direction = shipRef.position - transform.position;
//Assigns the vector to the camera
transform.forward = direction;
//Calculate the projection vector
Vector3 vpp = shipRef.position - shipRef.forward * CameraDistanceFromShip;
//calculate the new direction of the camera
Vector3 direction2 = vpp - transform.position;
//Apply the movement
transform.position += direction2 * CameraVelocity * Time.deltaTime;

```

This script is attached to the camera. You don't need to make the camera child of the ship

///***** *EDITED* *****///

So, I found This Orbit Camera.

I converted to c#, I think it is what you want.

```
public Transform target;
public float distance = 10.0f;

public float xSpeed = 250.0f;
public float ySpeed = 120.0f;

public float yMinLimit = -20;
public float yMaxLimit = 80;

private float x = 0.0f;
private float y = 0.0f;

public float smoothTime = 0.3f;

private float xSmooth = 0.0f;
private float ySmooth = 0.0f;
private float xVelocity = 0.0f;
private float yVelocity = 0.0f;

private Vector3 posSmooth = Vector3.zero;
private Vector3 posVelocity = Vector3.zero;

void Start ()
{
    Vector3 angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

    // Make the rigid body not change rotation
    if (rigidbody)
        rigidbody.freezeRotation = true;
}

void Update()
{
    //Calculate the vector between the camera and the ship
    Vector3 direction = target.position - transform.position;
    //Assigns the vector to the camera
    transform.forward = direction;
    //Calculate the projection vector
    Vector3 vpp = target.position - target.forward;
    //calculate the new direction of the camera
    Vector3 direction2 = vpp - transform.position;
    //Apply the movement
    transform.position += direction2 * 5 * Time.deltaTime;
}

void LateUpdate ()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        xSmooth = Mathf.SmoothDamp(xSmooth, (float) x, ref xVelocity, smoothTime);
        ySmooth = Mathf.SmoothDamp(ySmooth, (float) y, ref yVelocity, smoothTime);

        ySmooth = ClampAngle(ySmooth, yMinLimit, yMaxLimit);

        var rotation = Quaternion.Euler(ySmooth, xSmooth, 0);

        // posSmooth = Vector3.SmoothDamp(posSmooth,target.position,posVelocity,smoothTime);

        posSmooth = target.position; // no follow smoothing

        transform.rotation = rotation;
        transform.position = rotation * new Vector3(0.0f, 0.0f, -distance) + posSmooth;
    }
}

static float ClampAngle (float angle, float min, float max)
{
    if (angle < -360)
        angle += 360;
    if (angle > 360)
        angle -= 360;

    return Mathf.Clamp (angle, min, max);
}

```

---
Tags: c#, unity
---


# Question
Title: Create sprite renderer using custom material
I have done following thing.

1. Create Material
2. Attach sprite with texture type as Texture
3. Add sprite renderer component to game object
4. Assign material to it that I create in last steps

There is no sprite available for selection. Following image illustrate my problem correctly.

So my question in how to create sprite renderer with custom material?

# Answer
You must put a Sprite asset in the Sprite Renderer "Sprite" field. And you can assign any Material on "Material" field. You don't need to put a texture on the Material.
> 0 votes

---
Tags: unity, sprites, texture-atlas, materials
---


# Question
Title: Is there a benefit to applying forces to my camera?
I have implemented a camera system and a rudimentary physics system. I now have a decision to make regarding steering the camera:

*Option 1* \- Update the camera movement directly.

```
eg. position (0, 0, 0) + Key 'W' => position (0, 0, 1)

```

*Option 2* \- Apply a force to the camera and let my physic's integration sort it out.

```
eg. position (0, 0, 0) + Key 'W' + force (0, 0, 0.2) => ...?

```

How should I implement camera movement?

# Answer
> 2 votes
Take a look at the two images below. Both are of cameras. The first is a physical object. You can hold it in your hand and you can smash it to pieces with a hammer. The second is an abstraction. It occupies no physical space, it has no mass and it can't hurt you by falling on your toes.

It makes as much sense to apply physics to such an object as to apply gravity to gas prices or to do collision detection on a horror story. Give control over the camera to the player instead of to the physics engine. You can still use integration to make the camera move more smoothly, but don't apply forces. In fact, keep the entire camera far away from any physical calculations.

<sub>(source: geniusdv.com)</sub>

---
Tags: physics, camera
---


# Question
Title: Issue with calling Spritebatch in XNA 4.0 Game
So, I am creating a game in XNA 4.0, using the program Microsoft Visual C# Studio Express 2010.

The issue I am having: I have the entire game done, and there is no reason why it should not be working.

The issue is that every time I try to debug my game, it tells me that I am missing a 'Spritebatch.end' or a 'Spritebatch.begin' in random areas in my code. If I put in a 'Spritebatch.end', it tells me I am missing a 'Spritebatch.begin', and vice versa. I have gone over the source code of this repeatedly, and there is no syntax error.

So my question is: Is there an issue with the program I am using, or is there some other reason my code is giving me this rather circular error?

Here is what I have right now: I have implemented other fixes but nothing has worked.

```
private void DrawEmptyPiece(int pixelX, int pixelY)
    {

        spriteBatch.Begin();
        spriteBatch.Draw(
            playingPieces,
            new Rectangle(pixelX, pixelY,
                GamePiece.PieceWidth, GamePiece.PieceHeight),
                EmptyPiece,
                Color.White);
        spriteBatch.End();

    }

    private void DrawStandardPiece(int x, int y,
        int pixelX, int pixelY)
    {
        spriteBatch.Draw(
            playingPieces, new Rectangle(pixelX, pixelY,
                GamePiece.PieceWidth, GamePiece.PieceHeight),
                gameBoard.GetSourceRect(x, y),
                Color.White);

    }

    private void DrawFallingPiece(int pixelX, int pixelY,
        string positionName)
    {
        spriteBatch.Draw(
            playingPieces,
            new Rectangle(pixelX, pixelY -
                gameBoard.fallingPieces[positionName].VerticalOffset,
                GamePiece.PieceWidth, GamePiece.PieceHeight),
                gameBoard.fallingPieces[positionName].GetSourceRect(),
                Color.White);
    }

    private void DrawFadingPiece(int pixelX, int pixelY,
        string positionName)
    {
        spriteBatch.Draw(
            playingPieces,
            new Rectangle(pixelX, pixelY,
                GamePiece.PieceWidth, GamePiece.PieceHeight),
                gameBoard.fadingPieces[positionName].GetSourceRect(),
                Color.White *
                gameBoard.fadingPieces[positionName].alphaLevel);
    }

    private void DrawRotatingPiece(int pixelX, int pixelY,
        string positionName)
    {
        spriteBatch.Draw(
            playingPieces,
            new Rectangle(pixelX + (GamePiece.PieceWidth / 2),
                pixelY + (GamePiece.PieceHeight / 2),
                GamePiece.PieceWidth,
                GamePiece.PieceHeight),
                gameBoard.rotatingPieces[positionName].GetSourceRect(),
                Color.White,
                gameBoard.rotatingPieces[positionName].RotationAmount,
                new Vector2(GamePiece.PieceWidth / 2,
                    GamePiece.PieceHeight / 2),
                    SpriteEffects.None, 0.0f);
    }

```

And the rest of the code.

```
    protected override void Draw(GameTime gameTime)
    {

        foreach (ScoreZoom zoom in ScoreZooms)
        {
            spriteBatch.DrawString(pericles36Font, zoom.Text,
                new Vector2(this.Window.ClientBounds.Width / 2,
                    this.Window.ClientBounds.Height / 2),
                    zoom.DrawColor, 0.0f,
                    new Vector2(pericles36Font.MeasureString(zoom.Text).X / 2,
                    pericles36Font.MeasureString(zoom.Text).Y / 2),
            zoom.Scale, SpriteEffects.None, 0.0f);
        }

        if (gameState == GameStates.TitleScreen)
        {
            spriteBatch.Begin();
            spriteBatch.Draw(titleScreen,
                new Rectangle(0, 0,
                    this.Window.ClientBounds.Width,
                    this.Window.ClientBounds.Height),
                    Color.White);
            spriteBatch.End();
        }

        for (int x = 0; x < GameBoard.GameBoardWidth; x++)
            for (int y = 0; y < GameBoard.GameBoardHeight; y++)
            {
                int pixelX = (int)gameBoardDisplayOrigin.X +
                    (x * GamePiece.PieceWidth);
                int pixelY = (int)gameBoardDisplayOrigin.Y +
                    (y * GamePiece.PieceHeight);

               DrawEmptyPiece(pixelX, pixelY);

                bool pieceDrawn = false;

                string positionName = x.ToString() + "_" + y.ToString();

                if (gameBoard.rotatingPieces.ContainsKey(positionName))
                {
                    DrawRotatingPiece(pixelX, pixelY, positionName);
                    pieceDrawn = true;
                }

                if (gameBoard.fadingPieces.ContainsKey(positionName))
                {
                    DrawFadingPiece(pixelX, pixelY, positionName);
                    pieceDrawn = true;
                }

                if (gameBoard.fallingPieces.ContainsKey(positionName))
                {
                    DrawFallingPiece(pixelX, pixelY, positionName);
                    pieceDrawn = true;
                }

                if (!pieceDrawn)
                {
                    DrawStandardPiece(x, y, pixelX, pixelY);
                }
            }

        spriteBatch.DrawString(pericles36Font,
         playerScore.ToString(),
         scorePosition,
         Color.Black);

        base.Draw(gameTime);
    }

```

# Answer
It works when your `Draw(GameTime gameTime)` is like

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

     foreach (ScoreZoom zoom in ScoreZooms)
     {
      spriteBatch.DrawString(pericles36Font, zoom.Text,
      new Vector2(this.Window.ClientBounds.Width / 2,
      this.Window.ClientBounds.Height / 2),
      zoom.DrawColor, 0.0f,
      new Vector2(pericles36Font.MeasureString(zoom.Text).X / 2,
      pericles36Font.MeasureString(zoom.Text).Y / 2),
      zoom.Scale, SpriteEffects.None, 0.0f);
     }

     spriteBatch.DrawString(pericles36Font,
     playerScore.ToString(),
     scorePosition,
     Color.Black);

     spriteBatch.End();
     base.Draw(gameTime);
    }

```

I would recommend to move the `spriteBatch.Draw(...)` code from the private methods into your `Draw(GameTime gameTime)` and to comment all those private methods
> 1 votes

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


# Question
Title: How can I use the same number of tiles in any screen resolution, with an isometric projection?
I have an isometric grid with 64x32 diamond images. Each tile is a class, each instance is in a 2D array.

Players have different screen resolutions and the grid must take up the whole screen. Additionally, every player should always see the same tiles (so nobody has an advantage).

The only thing I could think of was to change the tile size: Bigger screen, bigger tiles.

I suppose I could do this by resizing my existing tile images, but is there a better way?

# Answer
1. Define 'supported' default resolution: 4:3, 16:9.
2. In 16:9, plan your grid as a 4:3 and put it on the left side of the screen, and have menu/control items on the right side of the screen (the side having a black or more appropriate background).
3. In 4:3, have your grid full screen but your menu/control items as overlays over your grid.
4. On other resolutions, check if it's more like a 4:3 or for a 16:9 and set up screen accordingly, then stretch/compress the result before displaying it full-screen.
> 0 votes

---
Tags: tiles, isometric, image, resolution
---


# Question
Title: Colour intersection of two alpha-blended sprites
In XNA, is it possible to merge two alpha blended sprites so they look like one contiguous shape, eliminating the merge of colour at the overlap? At the moment when I try, the intersection is quite visible:

I'd like it to look more like this mockup:

This is the drawing code for this example, but it's similar to what's being used in the actual game:

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null);

        for (int x = 10; x <= 1000; x += 10)
            for (int y = 10; y <= 1000; y += 10)
                spriteBatch.Draw(Content.Load<Texture2D>("dot"), new Vector2(x, y), null, Color.Gray, 0, Vector2.Zero, 1, SpriteEffects.None, 0.1f);

        spriteBatch.Draw(Content.Load<Texture2D>("circle"), new Vector2(200, 200), null, Color.FromNonPremultiplied(255, 255, 255, 50), 0, Vector2.Zero, 1, SpriteEffects.None, 0.5f);
        spriteBatch.Draw(Content.Load<Texture2D>("circle"), new Vector2(300, 200), null, Color.FromNonPremultiplied(255, 255, 255, 50), 0, Vector2.Zero, 1, SpriteEffects.None, 0.5f);

        spriteBatch.End();

        base.Draw(gameTime);
    }

```

I suspect the answer is somehow combining the textures before passing them to the spritebatch to be drawn, but I'd prefer to avoid that if at all possible.

Thanks for any help!

# Answer
You can try drawing on a texture in memory without alpha and then draws the result with the desired value of alpha.

This link tells you how to draw texture memory: http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series3/Render\_to\_texture.php
> 2 votes

# Answer
This is when I'd bust out the stencil buffer. It's like the depth buffer in that it's a per-pixel mask you can exploit for various effects. Your particular scenario is exceptionally well suited for its use.

When creating your GraphicsDeviceManager, you can configure the depth stencil format to request a format with some number of bits allocated for stencil operations. Once you have that, the rendering process is, at a high level, this:

1. Enable the stencil test and clear the stencil buffer to all 0.
2. Configure the stencil test to only accept new pixels where the stencil values are 0 AND to increment the stencil buffer value when a new pixel is accepted.
3. Draw all the shapes you want to mask this way.
4. Disable the stencil test.

What this does is prevent you from drawing to the same pixel twice because the stencil buffer will fail it.

I don't have code off hand but this answer seems to be a decent quick sample of using the stencil buffer. The other good resource for this is going to be the DepthStencilState documentation which exposes all the options for stencil tests.

Now there are some issues that will crop up with transparent sprites since the transparent pixels will still pass through the stencil test (thus your stencil will really be a rectangle, not the circle you see). The example code I linked uses an alpha test effect which should take care of that by discarding any transparent pixels, though I've not actually tried it myself.
> 1 votes

---
Tags: xna, c#, alpha-blending
---


# Question
Title: Can I rely on SoundEffects being stopped when unloaded?
I am using XNA's `SoundEffect` class to play sounds. I have to `unload` all sounds from the corresponding `ContentManager` for technical reasons, while some of them are still playing.

What happens to sounds that are still playing (via `SoundEffect` instances) when being `unload`ed? It seems that they just stop abruptly. Is this a deterministic behaviour I can rely on? Can it cause any errors when `unloading` sounds that are currently playing?

# Answer
When you call `Unload()` on the `ContentManager` it will internally call `Dispose()` on any object that was loaded that implements the `IDisposable` interface (which `SoundEffect` does). Therefore yes, it is deterministic that calling `Unload()` on the `ContentManager` will stop all `SoundEffect` instances as they are being disposed.

Shawn Hargreaves wrote a nice blog post about the `ContentManager` that details the extensibility points of `ContentManager` while also describing this default behavior.
> 1 votes

---
Tags: xna-4.0, sound, documentation
---


title: XNA SoundEffect with offset

text:
# Question
Title: XNA SoundEffect with offset
I've been trying to make a soundmanager recently which has several functions which fits my needs. But one thing I can't solve, is the offsetting the soundeffects.
Is it possible to play a soundeffect from a specific point? I know I have to use the buffering, but I couldn't find anything on the net about it. Any help would be appreciated!

# Answer
> 2 votes
When you say "from a specific point" do you mean "from a specific time" or "from a specific 3D location"? For the latter see this guide for how to do positional audio using `AudioListener` and `AudioEmitter` with `SoundEffectInstance`.

For the former, it's more complicated. The `SoundEffect` API doesn't easily expose this functionality. One approach would be to read in the raw PCM data and feed only the portion you want to play to the `DynamicSoundEffectInstance` class. It's a little annoying but should be perfectly doable.

XACT may offer you this functionality as well, though I'm not well versed enough to know for sure.

If you just want to resume a previously playing sound, look into use a `SoundEffectInstance`. If you play a `SoundEffectInstance` you can use `Pause()` to "stop" it rather than calling `Stop()`. If you pause an instance, you can just `Resume()` it to continue where it left off.

The bigger question I'd ask is what are you trying to achieve? I've not seen any examples where you'd author a sound effect and then want to start playback somewhere other than the beginning. I'd consider your actual goals and determine if this is the right solution for the problem you're actually trying to address.

---
Tags: xna, sound
---


# Question
Title: GameTime Replacement / Wrapper for Pausing , Slow-mo and 'Fast-mo'
I'm looking to change the way in which my game uses `GameTime` to run the game so that I can easily pause the game (`elapsedTime = 0`) or change how slow/fast the in game elements interact as a scaler of the actual time passed (`elapsedTime *= timeScale`).

In my project, I always make the assumption that the game is not running on a fixed time step for a number of reasons. Due to this, any changes of states have the elapsed time factored in from `GameTime`. I'm hoping this means I can simply simulate slow-mo, fast-mo, force short freezes (like when you kill an enemy in TLoZ: Windwaker - there's a short pause for emphasis) or pause the game by interfering with the `GameTime.ElapsedGameTime` that all of my `Update()` code uses.

My first thought is to stop using `GameTime` within any update code, and to instead wrap a new class (`MyTime`) around `GameTime`.

`MyTime` would do the following:

* Seperates real time and game time. Real time is the passage of time outside of the system. Game time is the passage of time within the game's world, i.e if slow motion is in effect, the time passed within the game would be lower for the period of slow motion.
* Time scaling can either be started and ended, or requested to be active for a length of real time or game time.
* Time can be paused or frozen with either manual start and stop calls, or for a length of time, again based on either real or game time.

Based on this discussion, where it's states that `GameTime` is recreated every tick within XNA's base `Game` class, I'm hestitant to just store a reference to `GameTime` within `MyTime` as I personally don't know how `GameTime` is altered. I also don't know the 'best' way to retrieve the `GameTime` reference in the first place, the reference is available within the `Update()` and `Draw()` calls, however since `gameTime` isn't made available throughout any derived from `Game` class, it's implied taking the `gameTime` reference out of those update and draw calls isn't intended.

Is my intended implementation of this the right way of achieveing this system? What is a good to expose `GameTime` to `MyTime`? Should I implement my own way to track time and not rely on `GameTime` at all?

# Answer
I would still use `GameTime` to track the passage of time (no sense reinventing that wheel), but I would not bother storing it in your `MyTime` object and you certainly shouldn't try to subclass `GameTime`. Just create your own type with whatever fields you want and then use the `GameTime` provided to the `Game` class to update your instance however you want, applying your time scale, etc. This gives you full customization of the timing structure without having to worry about how the `Game` stores/updates the `GameTime` object.

Edit: Humorously I'm going against my own advice in that link but you learn a thing or two from six additional years of game development. So listen to me by not listening to me. :)
> 2 votes

---
Tags: xna, c#, timestep, time-travel
---


# Question
Title: How do I detect how much of an object has been "cleaned" by the player?
I want to let the player wipe some dust off of a book, then start a short animation.

Here's what it looks like:

I'm using a clipping region on the "dusty" book bitmap image to progressively hide the dust as the player mouses over it.

However, I'm stuck with how to detect when the dust is all gone. What's a good way of tracking how much is left?

# Answer
At the moment, you seem to be changing only the *view* (what objects look like), rather than the *model* (what their state is). (I'm using the MVC terms.)

How about this for a model:

It's a grid of hotspots.

Now, when the mouse is pressed, you could set the closest point on the grid to a `true` value. The percentage cleaned would then be the ratio of `true` spots to total spots.

You can of course adjust the grid density to whatever works for you.
> 1 votes

---
Tags: 2d, graphics, flash, clipping
---


title: How to clamp player movement correctly?

text:
# Question
Title: How to clamp player movement correctly?
I have a 2D space shooter game. I looked up some questions from unity community and came across this solution. Below is the code for my player's movement:

```
//horizontal <- || -horizontal ->
//vertical down || -vertical up
float h = -Input.GetAxis ("Horizontal")*speed;
float v = -Input.GetAxis ("Vertical")*speed;

// do not let the ship get out of the camera
Vector3 viewPosition = Camera.main.WorldToViewportPoint(transform.position);
viewPosition.x = Mathf.Clamp01(viewPosition.x);
viewPosition.y = Mathf.Clamp01(viewPosition.y);
transform.position = Camera.main.ViewportToWorldPoint(viewPosition);

transform.Translate (h, v, 0);

```

I understand these functions as 0,0 being the left bottom of the camera and 1,1 being the right top. Therefore `clamp01()` is used. But with this code, half of my ship gets out of the screen, which is not what I want. How am I supposed to manipulate the clamp01 function so that the entire ship of the player stays in the camera scene?

Another workaround I thought was using the screen width and height and the regular `clamp()` function as follows:

```
transform.Translate (h, v, 0);

Vector3 tmpPos = transform.position;
tmpPos.x = Mathf.Clamp (tmpPos.x, -Screen.width / 2, Screen.width / 2);
tmpPos.y = Mathf.Clamp (tmpPos.y, -Screen.height / 2, Screen.height / 2);
transform.position = tmpPos;

```

However I get the `Screen.height` as 428, although the camera sees the interval of \[-10, 10\]. How am I supposed to clamp the movement independent of the game resolution, i.e. not using global positions but using relative positions so that I will be able to clamp correctly player's ship whatever the resolution of the game is?

# Answer
Your first approach fails to account for the width of the object, while your second approach fails to account for the difference between screen pixels and world coordinates.

---

I have always converted the extremes of the screen to world coordinates.

```
Vector3 bottomLeftWorldCoordinates = Camera.main.ViewportToWorldPoint(Vector3.zero);
Vector3 topRightWorldCoordinates = Camera.main.ViewportToWorldPoint(new Vector3(1,1,0));

```

When you perform your clamping in world coordinates it is easier to apply an offset for the object width.

As the position is (often) the center of the object you will need to calculate half it's width and offset your clamp accordingly. Likewise on the y-axis.

A good source of half-width and half-height values is often `renderer.bounds.extents`.

```
Vector3 movementRangeMin = bottomLeftWorldCoordinates + renderer.bounds.extents;
Vector3 movementRangeMax = topRightWorldCoordinates - renderer.bounds.extents;

```

You can then use these value to clamp the object to the screen.

```
Vector3 newPosition = transform.position;
newPosition.x = Mathf.Clamp(position.x, movementRangeMin.x, movementRangeMax.x);
newPosition.y = Mathf.Clamp(position.y, movementRangeMin.y, movementRangeMax.y);
transform.Translate(newPosition - transform.position);

```
> 1 votes

---
Tags: c#, unity, camera, movement
---


# Question
Title: How do I best solve multiple component modifications via a single event?
I'm trying to solve multiple component modifications via a single event. Is there a better way of handling this?

I have an a label entity that cares about when a shield entity's hitpoints component is modified (damage, regeneration, etc).

The label will need to change

* its text to display the current % of shield remaining.
* its text color to display the severity of shield remaining.

When my `ShieldSystem` resolves the `hitPoints` component, the below code runs. For eah type of modification I plan to listen for, I need to add a new `if`-statement to the `for`-loop. This means I have a bunch of duplicated code between systems if more than one wants to modify any listening text component, sprite component, etc.

```
for(int i =0; i < listeners.size(); i++)
{
    if(listeners.count(MessageType::CHANGE_TEXT) == 1)
    {
        std::vector<Entity*> entities =  listeners[MessageType::CHANGE_TEXT];
        for(int j; j < entities.size(); j++)
        {
            Entity* e = entities[j];
            MessageInfo* messageInfo = new MessageInfo(MessageType::CHANGE_TEXT, e, "Some Text");
            MessageCenter::Dispatch(messageInfo);
        }
    }

    // Add an If(listeners.count(MessageType::CHANGE_TEXT_COLOR)...

    // Add an If(listeners.count(MessageType::CHANGE_SPRITE_RECT)...

    // etc

}

```

# Answer
One way to make this easier to use is to let a user emit message types.

Check out some example implementation (see Messenger.h and .cpp).

The idea is to let a user do something like this:

```
// Subscribe to a particular message type as a user
messenger.Subscribe( MSG_type, CallThisFunction );

// Notify the client
messenger.Emit( MSG_type ) // calls CallThisFunction

```

A good way to pass along parameters with a message is to have some generic way to send data. Then you can let the user (in this case inside of `CallThisFunction` deal with retrieving the data appropriately (typecasting, or some other more intelligent means). This lets the notifier use an alternate Emit version:

```
// Notify the client with 4 params, pass each
// param to the CallThisFunction
messenger.Emit( MSG_type, somePtr, 5, 1.0f, "a string" );

```

All in all this mostly looks like an API issue.
> 1 votes

---
Tags: entity-system, events, messaging
---


# Question
Title: How do I ensure that my 2D side-scroller camera stays within the world bounds?
I have tried implementing a basic 2D sidescroller camera in XNA, but I don't want it to be able to scroll past the edges of my tile map!

I tried to fix it, but when I get the left side working, the right stops working...

How do I do this right?

EDIT: After Anko

```
public Matrix transform;
Viewport view;
Vector2 center;

public void Update(GameTime gameTime, Player player) {
    center = new Vector2(player.Position.X + (player.Bounds.Width / 2) - (960 / 2), 0);

    float cameraX = center.X;
    float cameraWidth = view.Width;

    float worldWidth = 1760;

    if (cameraX < 0)
        cameraX = 0;
    else if  ( cameraX + cameraWidth > worldWidth)
        cameraX = worldWidth - cameraWidth;

    transform = Matrix.CreateTranslation(new Vector3(-cameraX, 0, 0));

```

# Answer
> 4 votes
Let's draw it! <sub>(Again ;3)</sub>

Imagine all the grassy and skyey bits are your game world. That lighter coloured rectangle framed in red is the region the camera is looking at. A player would only actually see what's in the camera. We want the camera to always stay in the game world.

`(x,y)` is the camera position
`w` and `h` are the camera's width and height

Let's also say your game world has width `world_w` and height `world_h`.

To take care of left, we want to ensure `x > 0`
To take care of right, we want to ensure `x + w < world_w`

To take care of the top, we want to ensure `y > 0`
To take care of bottom, we want to ensure `y + h < world_h`

So, before you apply a transformation matrix to translate by `x, y`, check that our assumptions indeed are true, and if not, correct them so they just about are:

```
if x < 0 then
    x = 0
elseif x + w > world_w
    x = world_w - w

if y < 0 then
    y = 0
elseif y + h > world_h
    y = world_h - h

```

No more escaping camera!

Note that you might want to build in a special case to detect if your world is smaller than your camera, if such a tiny world might happen in your game.

---
Tags: xna, camera, monogame, platformer, side-scroller
---


# Question
Title: Tangent plane vectors smoothing with vertex normals
I'm trying to find a way to smooth out normals obtained from cross product of tangent and bitangent vectors calculated per face basis. I've already asked a similar question on SO, however with no answers so far.

Trying to come up with a solution (and also being bad at math) I decided to use the normals I obtain from the model file, since they are already given per vertex and transform each of the tangent plane vectors by rotation matrix obtained from dot and cross products of the calculated and loaded normals.

Now, this *looks* ok and the lighting is nice and smooth, however I have no idea if this solution is actually correct and, if no, what may be the problem with it. I assume it's not best as I haven't seen anything like it elsewhere.

Here's the part of the code which implements the idea. `tangent` `bitangent` and `normal` are the vectors computed per face. `normal1` `normal2` etc. are vertex normals.

```
    D3DXVECTOR3 axis;    // rotation axis
    D3DXVECTOR4 temp;    // temporary vector for rotation result
    D3DXMATRIX rotation; // rotation matrix
    float cosAngle, angle;

    // Vertex 1
    // Find rotation axis and angle between face normal and vertex normal
    cosAngle = D3DXVec3Dot(&normal, &normal1);
    angle = acos(cosAngle);
    D3DXVec3Cross(&axis, &normal, &normal1);
    D3DXVec3Normalize(&axis, &axis);

    // Create rotation matrix
    D3DXMatrixRotationAxis(&rotation, &axis, angle);

    // Transform each of the vectors
    D3DXVec3Transform(&temp, &normal, &rotation);
    normal1.x = temp.x;
    normal1.y = temp.y;
    normal1.z = temp.z;

    D3DXVec3Transform(&temp, &tangent, &rotation);
    tangent1.x = temp.x;
    tangent1.y = temp.y;
    tangent1.z = temp.z;

    D3DXVec3Transform(&temp, &bitangent, &rotation);
    bitangent1.x = temp.x;
    bitangent1.y = temp.y;
    bitangent1.z = temp.z;

    // do the same for vertices 2 and 3...

```

# Answer
You can calculate smooth tangent/bitangent vectors the same way that people usually do smooth normal vectors. That is, calculate them per face, then for each vertex, calculate the average of the vectors over all the faces that use that vertex.

This will work OK, but on some models you'll run into problems around UV seams, where the tangents and bitangents tend to change direction sharply. Generally speaking, wherever there is a UV discontinuity there will be a tangent/bitangent discontinuity as well.
> 1 votes

---
Tags: c++, directx, vector, normals
---


title: How can I distribute powerups "fairly"?

text:
# Question
Title: How can I distribute powerups "fairly"?
I'm implementing a *Bomberman*-esque game in which players try to eliminate each other on a square tile-based arena. I'm currently implementing powerups that give the player who collected them a bonus (such as a larger inventory or faster movement speed).

How should the game system place these powerups such that, provided players collect powers closest to them, the game remains fairly balanced?

My first approach was to spawn a powerup on a random empty tile every few seconds. The problem with this purely random approach is that a player can have a massive advantage early in the game just by the luck of having many powerups spawn near them.

Ideally, I'd like powerups appear equally often near each player, but occasionally spawn near the map's center to encourage competition. To be clear, I do want *some* element of randomness -- specifying exactly which powerups spawn when and where would make the game predictable and dull.

What alternatives exist?

# Answer
> 8 votes
An alternatve would be to not place the power-ups near the players but at positions which involve taking some risks to get there. This way you would encourage players to stop hiding which can increase the fun-factor and would reward them for their "courage". On top of that no one could complain that someone was just lucky to pick up a powerful power-up although a certain randomness is still preserved (if you just happen to be in the area and a really powerful power-up appears, or a rather useless power-up, etc.).

2nd idea: Like in Mario Kart you could favour the weakest player and increase the odds of him getting more powerful items. This way it would also be fun for weak players to play against more advanced ones. However, you must be careful to not counter-act every smart move a player makes with your algorithm, or else you will force the players into a draw situation making the entire game rather dull as no one can really win.

# Answer
> 1 votes
I agree with the previous answer about taking risks. However if you do specifically want to weigh the randomness to counter advantage, you could do something like this:

1. For each player generate a random point somewhat near their current position (but not too close). For example, pick a random angle. Pick a distance, e.g. min\_dist + rand ^ 2. Calculate the point that angle and distance from the player and restrict to the playing area.
2. Combine the random points weighted by how much advantage you want to give each player.

Or alternately:

1. Pick x completely random points.
2. Use the random point whose distance best matches the advantage ratio.

# Answer
> 1 votes
In Bomberman powerups are spawned through player action. When a player destroys a block there is a chance that a powerup is spawned on the tile of the destroyed block. Perhaps your game should tie powerup spawns to player action.

Let's say your game has destructible blocks like Bomberman. Whenever a block is destroyed it would have a chance to spawn a powerup. It could be a flat chance per block, say 10%. A flat chance like this would technically be fair for all players, but might give somebody a really lucky streak of multiple powerups in a row or a really unlucky streak of no powerups for a long time.

Instead of using a flat chance for each block you could use a progressively growing chance and track it per player. The chance would start small, let's say 1.5%, and then grow each time a powerup is *not* spawned. When a powerup *is* spawned the chance drops back down to its original value (1.5% in our example).

So let's say a player destroys a block and the RNG rolls with a 1.5% chance. The roll is unsuccessful so the chance for that player is increased by 1.5% up to 3.0%. The player again destroys a block and gets no powerup. so the chance on the next block goes to 4.5%. When the player finally spawns a powerup, and they eventually will since the chance continues to increase, their chance on the next block reverts back to the base value of 1.5%.

This system has a couple advantages to a flat chance across the board:

1) It minimizes really lucky streaks because after a player spawns a powerup their chance on the next block drops dramatically.

2) It minimizes really unlucky streaks because the player's chance to spawn a powerup continually grows until it eventually reaches 100%.

You can also adjust the base chance per player depending on their score or other factor. If you want the losing player to have a chance for a comeback you can set their base chance at 2.5%, increasing by 2.5% each "miss."

---
Tags: game-design, game-mechanics, tilemap, random
---


title: Nintendo 3DS copy protection

text:
# Question
Title: Nintendo 3DS copy protection
I bought an old second-hand Nintendo DS game from a used game shop and my 3DS wouldn't play it. I exchanged it and the shop said it was probably a forged cartridge.

I did a bit of research and apparently the 3DS has better forgery detection than the older models - so the fake cartridge probably worked in an old DS but not in my newer model.

Here's what I already understand about 3DS copy protection:

* Modern cartridges have a cryptographic signature to prove they're genuine.
* Older cartridges have no signature, but the 3DS has a whitelist of checksums for every legitimate old cartridge.
* Cartridges that don't have a signature OR appear on the whitelist are blocked.

I can see how this would stop me releasing my own unlicensed game. But I don't understand why it blocks a copy of an existing, legitimate game.

**My question is**: why can't the game pirates make a perfect copy of an existing game, including the signature (or with a matching checksum), so the 3DS can't distinguish it from the real thing?

(Aside - I've got no interest in playing pirated games (I write software for a living myself), I'm just curious about the technology).

# Answer
> 1 votes
Things like this aren't just about providing a checksum or serial number as part of the program or image. That would be too easy to trick.

In such situations one basic paradigm would always be true and important: "don't trust the image" (at all).

It's more likely the checksum is created on startup (doesn't have to include the whole image data to speed up loading times), and then compared to an internal whitelist.

This way it's way harder (or next to impossible) to trick the console to think the game would be something else.

Signatures work in a similar way, it's just so that the "whitelist" is essentially provided as part of the image as well.

**Why can't they just create a matching checksum?**

That's easy to answer: Because it is a checksum. A checksum is supposed to change, even if there are only slight changes to the source. Of course, there will be collisions (since the checksum has a lower entropy than the actual data), but it's still most likely too hard or almost impossible to achieve this. You can't change all the code just to match the checksum, because you'll most likely have to change more than one or two arbitrary or unused values.

**Why can't they make a perfect copy of an existing game?**

That's the better question. I'm not 100% sure, but I'd assume that it might not be that easy to get the raw image and the actual data read already depends on the actual hardware accessing the data. To provide a similar example: It's not that easy to read or write a CD or DVD "as-is" simply because of the firmware doing its own processing/error correction as well. In a similar way, you can't tell a burner to exactly write the sequence `001100110011` to the disc. It will do so, the data read will still be the same as well, but the actual/physical data will have a different pattern/representation (e.g. due to error correction/redundancy stuff).

---
Tags: nintendo
---


# Question
Title: How can I delete an enemy's bitmap from a canvas?
I'm learning to create an Android shooter game where I'll have multiple enemies. I must control the position on the screen and be able to delete each of then (via, for example, a `die()` function).

But I use a canvas, which is most recomended, is it possible to delete just one bitmap and not the entire canvas (by delete I mean make it vanish from the screen, not just erase its value)? If so, how?

Another approach, I guess, would be using the Android image view, which can be deleted and as well as controlled and positioned, but I think that can make my game run slow if I create various objects of a class enemy; is that correct?

# Answer
This sounds a bit like you've got a basic design error in your game.

When displaying scenes on the screen, games typically follow the following pattern:

* Delete the screen
* Draw everything
* Display the screen

Thanks to double buffering, this isn't as noticeable as you might think (i.e. there's no flickering).

So what you'd have to do is the following:

* Clear the screen. Based on how you draw the game, you might be able to skip this step.
* Draw the background.
* Draw all characters (whether they're spaceships, mushrooms, or whatever)
* Present the screen (i.e. swap buffers).

The whole process also varies slightly based on the actual drawing technology you're using (e.g. Canvas vs. OpenGL ES). In either way, you should only draw to one big screen. Don't try to draw everything into its own canvas element or anything like that.
> 1 votes

---
Tags: android, movement, character
---


# Question
Title: Why does my camera break mouse position targeting?
I made a short video of this.

Basically, when the screen scrolls with the camera, the character begins firing at the incorrect mouse position. You can see where I am clicking the whole time. As we move towards the right edge (the more we scroll), you'll notice the distance away from the correct position increases. The shooting mechanic worked just fine before I added the camera.

I'm using a translation matrix to implement my camera.

What could be causing this?

# Answer
> 0 votes
All objects within the game can interact with one another in a persistent manner regardless of camera location. However, items that aren't within the game cannot. Whatever translation the objects have undergone, the opposite needs to be done before the mouse can interact with them. For example

Say you more all objects using `xOffset` by 500px, you then subtract `xOffset` from all objects so that they appear to be in the correct place. if you wanted the mouse to interact with them, you'd have to add the `xOffset` back onto the Mouses x coordinate.

---
Tags: xna, 2d, camera, monogame, mouse
---


# Question
Title: Games development with a game loop that's abstracted away
Most game development happens with a main game loop. Are there any good articles/blog posts/discussions about games without a game loop? I imagine they'd mostly be web games, but I'd be interested in hearing otherwise.

(As a side note, I think it's really interesting that the concept is **almost** exclusively used in gaming as far as I'm aware, perhaps that may be another question.)

Edit: I realize there's probably a redraw loop somewhere. I guess what I really mean is a loop that is hidden to you. Frames are something you as the developer are not concerned with as you're working on a higher level of abstraction. E.g. `someLootItem.moveTo(inventory, someAnimatationType)` and that will move from the loot box to your inventory using the specified animation type without the game developer having to worry about the implementation details of that animation.

Maybe that's how "real" games end up working, but from reading most tutorials they seem to imply a much more granular level of control is used, but that might just be an artifact of being a tutorial.

Edit2: I think most people are misunderstanding what I'm trying to ask, likely because I'm having trouble describing exactly what I'm trying to ask. After some more thinking perhaps what I'm referring to is more along the lines of what I believe is referred to as "scripting" where you're working at a very high level and having some game engine take care of the low level details.

For example, take custom maps in Starcraft II or Warcraft III. Many of the "maps" have gameplay that deviates enough from the primary game that they could be considered a separate game written on the same engine. What I'm referring to then is along those lines. I may be wrong because I only dabbed in the Warcraft III editor, but as far as I remember no where in the map editor do you control the game loop, and yet you can create many different games out of it. In my mind, these are games in their own right. If you're playing DotA you don't say you're playing Warcraft III, you say you're playing DotA because that's the actual game you're playing.

Such a system may impose limitations that don't exist if you're creating a game from scratch, but it greatly reduces development time because much of the "hard" work has already been done for you.

Hopefully that clarifies what I'm asking. Another example of what is I mean, is when you write a web app, of course it communicates through sockets and TCP. But does the average web developer doesn't explicitly write code for connecting sockets. They just need to know about receiving a request and sending a response. There are unique scenarios where you do occasionally need to use raw sockets, but it's generally rare in web development.

In a similar fashion, it's very possible to write a game without directly using the game loop, even though one is used behind the scenes. Probably not a AAA title, but there must be hundreds of smaller scale games that can and possibly are written this way. Are there any good resources on writing these "simpler" games?

# Answer
> 8 votes
First off, I don't think it is possible to have a game that doesn't have a loop, somewhere, unless it is absolutely trivial. A web game uses a loop, the only difference is that you aren't writing the loop, you generally just respond to events. There is still a loop happening. In a way, the distinction is immaterial anyways, you generally must repeat a sequence of code many times. If you use a loop to do so, then fine, if you use events or some other mechanism, great: the end result is that you are repeating. A loop just seems to be the more straightforward way of repeatedly executing a block of code without overflowing your stack. ;)

I can't think of any other paradigm other than event-based when there is no explicit loop, so maybe you can describe what it is you are having difficulties with or want more information about. Is it a general question of how to structure code, or how stuff gets done? For example, in Javascript/HTML5 I'd use a repeating timer to send an event every 1/30 of a second to signal the drawing of a new frame of animation.

# Answer
> 2 votes
The only way I imagine you can avoid a game loop is recursion, which would eventually end in a stack overflow. Even if a game is event-based, there's something outside the game looping and sending those events. IE: Flash triggering tick/update/draw events. Inherently, to have more than a single frame of a game, you need to loop. That or your game is limited to a certain number of frames that are precomputed. That limits you to a rather simple game that isn't very actively... interactive.

# Answer
> 1 votes
Panda3D is entirely event driven, so the main loop of all games written in it is implicit really (one call to a library function that doesn't return until the game ends).

# Answer
> 0 votes
It's not entirely clear what you're asking. It's certainly possible for there to be no explicit game loop, eg. when the operating system essentially does your loop for you, but very little changes as far as the game is concerned.

1. Instead of calling update() in an explicit loop, you could put that function in an OnIdle handler or other Idle event callback - what exactly to use for that would be platform specific. If you have no idle events provided by your OS then you could simulate these with another thread that sets a condition each time you need to update.
2. Instead of polling directly for input, you respond to input events and then cache any values that you later need to poll for (eg. in the update function).
3. Instead of rendering directly, you might have to render in an OnPaint handler or something similar.

Beyond that though there's no real difference. However, I'm not convinced that's actually what you're asking, because you seem to be asking about how complex time-based actions take place in AAA games and the like.

> E.g. someLootItem.moveTo(inventory, someAnimatationType) and that will move from the loot box to your inventory using the specified animation type without the game developer having to worry about the implementation details of that animation.

If the 'game developer' didn't have to worry about it, someone else did. Probably the same developer, earlier in the development cycle. :) Motion over time can be handled by creating an object or system to monitor that motion. Each update() call moves the item towards the destination until it arrives, at which point the motion stops.

> Maybe that's how "real" games end up working, but from reading most tutorials they seem to imply a much more granular level of control is used, but that might just be an artifact of being a tutorial.

Pretty much. A much more granular level of control *is* used, and most games *do* run frame by frame, but most gameplay code won't need to take that directly into account. If I call `walkTo(14, 15)` then there is a separate system that slices that walking behaviour up over as many frames or loop iterations as takes to reach that destination. Same thing with something trivial such as `mario.jump()`. He still moves frame by frame, but there's a physics system that runs each frame which decides exactly how to move the guy. When you type mario.jump() you don't need to worry about how jumping is implemented - but *someone* had to work it out and implement it.

# Answer
> 0 votes
> Are there any good articles/blog posts/discussions about games without a game loop?

No. Every electronic game thats some sort of updates in real time use a game loop. The Only kind of game that wouldn't really use a game loop would be txt based game that reacts to user input only.

> I guess what I really mean is a loop that is hidden to you.

Sure, but even though it is hidden, everything applies. Flash for example has a loop for code execution, and you cannot specifically edit the main loop, you however can use different events to trigger code, or have code on the timeline which flash executes when it hits it.

> . E.g. someLootItem.moveTo(inventory, someAnimatationType) and that will move from the loot box to your inventory using the specified animation type without the game developer having to worry about the implementation details of that animation.

That is easily doable, but the thing is, someone has to set up that Method and set up the animation. **Game Development is not magic.**

# Answer
> 0 votes
Loops are simple constructs, and they're generally easy to implement. They work on a simple synchronous environments of things happening in some definite frames. All this nicely explains while a game loop (which is not necessarily a `while (true)` kind of thing - that's an implementation detail) is so popular in game engines.

However, the synchronicity breaks apart quickly as you make the game more complex - a prominent example being the addition of multiplayer features. Asynchronous actions are a very poor match for game loops. Suddenly, you're doing tons and tons of work to synchronize *somehow*, your abstractions leak like crazy and you're dealing with tons of bugs and latency issues and everything.

Now, most multiplayer games still use game loops, but to a big degree, this is so for performance reasons and familiarity. As compilers and virtual environments and computers themselves get better and better, we're getting more options to add abstractions that fit the asynchronous model better. Granted, in the end, there might be some loop hiding under all these abstractions (at the very least it's down there in the OS :)) ), but we don't care about the "loop-as-implementation-detail", we are interested in the "loop-as-abstraction".

A great example of a game that dispenses with the usual game loop is EVE online, and I do mean the client. That's why the client is (partially) written in Python - the whole GUI is made using asynchronous patters, tasklets. Basically, when you click a button, it starts an asynchronous flow that eventually results in you getting eg. a window showing current market data. The usual synchronous flow would be "button press -\> ask the server -\> get the data -\> show the form". This is all fine and dandy as long as the "ask the server -\> get the data" part is very fast - it has to take much less time than a single frame. If it's not fast enough, using the synchronous model means that your game updates / frames lag while the data is received. And combining the asynchronous model with a simple game loop gets tedious very soon. Suddenly you're crawling through tons of queues, and concurrent collections, and you have no idea what happens when and why, and all your code is full of if's and switches and state machines...

In practice, tasklets are basically syntactic magic ("syntactic sugar" doesn't quite cover it). You're writing code as if it were synchronous (simplicity), but it is actually executed asynchronously, without giving you the headaches of multi-threading. If you're not familiar with Python, a related concept is `await`/`async` in C#. The concept isn't all that new, it's the fact that it works pretty much automagically. Instead of hacking your game loop like crazy, you're back to the simple synchronous model - that automatically happens asynchronously (and in fact, without creating useless threads that are stuck on I/O operations).

This is IMO the future for GUI-heavy multiplayer (especially MMO) games. It vastly reduces the complexity of the code, and we can now easily afford the performance loss (which is actually quite low nowadays). And as the gap closes even more, it might one day become the go-to solution for everything. Perhaps the thing that enables this will be that everyone will have a 100-core CPU where each core is running at 500 MHz (after all, look at the GPU :)), or maybe the abstractions will have their overhead lowered enough to be even more negligible than today. And the garbage collector will be "free" and ...

Another interesting concept for basic game architecture is things like reactive frameworks (ie. when you get shot, the damage is propagated to all the observers of your health, and they can update at the very moment, rather than checking every single frame if you have been damaged). As the performance gap closes, and the game get less bound on "100% CPU", those abstractions gradually become more and more viable, and in fact, writing a multi-threaded game without those abstractions is a huge pain.

So, just like game development moved from assembly, through C, C++ to Java, Flash, .NET... it will move to even higher abstractions as long as they are better suited for the task at hand. Is there still a loop in there somewhere? Sure. Does it matter? Hell no.

# Answer
> 0 votes
The problem with games is they need things to be done in a specific order. Physics must be done before graphics because otherwise what would be the point of drawing the picture if nothing changed. Scripting needs to be done before physics since if you move an object the physic engine needs to process it.

The only alternative I could think of would be a distributed Actor model.

Basically each object is given control of it's own resources and everything must talk to it through some communication channel such as a message que. It could be done with shared memory across threads, over IPC for separate processes or networked for separate systems. It can be massively parallel (each object could potentially have it's own thread).

There is all kinds of fancy shenanigans you can pull, your objects could be on different servers, with IPv6 you could even give each object it's own ip address, of course it makes sense to keep objects likely to interact together on a thread to cut out overhead but maybe each level/chunk has it's own server process and the player is transferred from process to process.

That would result in a lot of overhead. But for some game types it might be ok, a SNES style MMO JRPG might be fine but not a FPS.

Physics might be kind of complex in such a situation. It would be non-deterministic since you can guarantee the order of operations, that would make saving/loading/replays unstable and mean more network overhead since you can't just transfer the state and let the client simulate it. But not everything needs physics other than basic collisions. Although even that can still have issues, if you step into a space at the same time as another character, who gets right of way? Different systems might see a different result depending on where they are located.

Rendering the graphics would be a pain since it would have to 'ask' each object to report its position each time (or request a subscription to be told when the location of any visible objects is changed and also request to be informed when a object becomes visible to the camera or is created). This could end up with a lot of chatter.

Another idea is an event loop. Probably not as a replacement for a main game loop but more for things like resource management. Rather than loading a directory of textures you could spawn a thread and tell it to 'watch' that directory. Any time it sees a file that hasn't been loaded it can spawn off another thread to handle the I/O. It can return 'dummy' objects for placeholders that then load the real object into place when ready. A nice feature is your game can be edited live. It can watch the filesystem for changes and when you edit a texture the game can pull it in straight away. You could also have things 'pop' into existence which might be useful for something like a virtual world (ie Second Life). Or you could have low detail ones that then resolve into clearer images.

# Answer
> 0 votes
What I understand of your question, with its edits, is that you're writing a game by coding, but never actually writing any of the code that is executed on every single frame. For instance, rather than:

```
onFrame()
    drawMarine()
    if (collisionTest(marine, cutsceneTrigger)) {
        gameState = cutscenePlaying(C1M1_FranklinDies);
    }
}

```

You'd just specify in a designer mode system, that when `marine` collides with `cutsceneTrigger`, then start playing `C1M1_FranklinDies`. Very little of this has to do with a "loop".

In some ways, I think your example of X-Craft's editors is well-put. Many people have even made entire mods for Half-Life 2 with just levels and various triggers in the Hammer Editor. Those are abstracted game systems in many senses. The reason people don't all make their games in the StarCraft 2 editor is a mix of game exposure/licensing, and the need for more fine-grained control.

In addition, some engines like Unity can help in terms of only exposing you to code on actual events, like collision, or more expanded time intervals; and do so without being specialized to specific types of games like RTSes.

All game engines will have that loop at the low level, so what you're essentially looking for is using a helpful engine without doing much of the base-level coding. That may remove your capabilities a little bit, but for many games that's not a concern.

---
Tags: game-loop
---


# Question
Title: Why do modern games not feature extra lives?
In the late 80s and early 90s, most games had an *extra life mechanic*. The player started with limited lives (often three) and dying depleted one of them. If they still had some remaining, they would respawn at the last savepoint. The game would end once all lives had been used and they had to start from the beginning. Players could obtain additional lives during the game.

This mechanic was so widely used that it was rather the exception when games *didn't* use it. It was and still is one of the most recognized video game clichés (the above image has been printed on countless shirts).

Nowadays, this mechanic seems to have been forgotten.

Almost every modern game gives the player infinite retries from the last save. Many even let the player make their own savepoints with a quicksave mechanic. Those few that try to be different tend to go for the other extreme: The "roguelike" mechanic gives the player no retries.

What happened to the middle-ground of having extra lives? What game design revolution caused the game industry to abandon this feature?

*When proposing an answer to this question, please try to back up your answer with citations and factual, objective evidence as much as possible so as to avoid dragging this post into the territory of being "too opinion-based." Focus on "what" happened and "when," which specific examples.*

# Answer
> 39 votes
Finite amount of lives in video games was a design element inherent to coin operated arcade gaming machines. In order to limit a player's play time so he would be forced to spend more coins or make room for the next player, a finite lives system, coupled with high difficulty, proved successful, so it became the standard for all of arcade gaming.

As home gaming consoles grew more popular, their games were of course made by the people already in the industry, so game design just stuck to what they know - high difficulty, limited number of lives, which led to the popular "nintendo-hard" label, referring to NES games.

As arcade machines declined in popularity and video game design matured, the concept of limited lives slowly fell out of favor. It typically made way for quick saves and instant, infinite restarts with short levels (think Super Meat Boy), in order to preserve the flow of a game, as opposed to setting back the player to the beginning of a level or checkpoint as a punishment for failure.

# Answer
> 3 votes
tl;dr: There was a saving mechanic in many older games: See Sega's SMS: Phantasy Star, Y's, Golvellius and WonderBoyIII. Also see Nintendo's ES: Metroid, Rygar and Zelda. Sometimes saves were based on (long) passwords. So the shift is not as strong as you would suggest. The main reason for the shift was replay value.

Long answer: In the old days there was no web access. If you check to see when the statistical shift happened between having three live and sometimes "continues" to having a quick-save or simply having the game remember the last level or checkpoint you visited, it was around the time that web access became more widely spread. Web access encourages the player to shift her attention rapidly. If a game is too hard and the player has to start over from scratch it's likely that player will abandon the game at that point and possibly never try it again.

In the old days a game could not afford to give you infinite lives? That would be a fallacy to state that without mentioning games like Y's, Phantasy Star, Final Fantasy and some others that had a saving mechanism built in already. Also in games like SMB3 you practically had access infinite lives (you could use the skeleton turtles to get them).

The reason many games could not afford to provide you with infinite lives was that it would make the game-play experience (of getting from start to finish) too short and therefore (in the eyes of some players) nearly exhausting the enjoyment that could be had with that game too soon. That was considered a fault back then because there was no web to let you hop directly to the next game; Games were often bought by parents and played by kids and if the kids whined that they needed / wanted a new game too soon, the game would probably not be considered a sound investment. Gamers and their parents wanted to get the most out of their money so a game had to be long, highly challenging and maze-like (See Phantasy Star and to some extent Y's, Golvellius and WonderBoy III) or artificially increase challenge by having a limited number of tries to get from start to finish (so you practically never see the ending or only after a long effort) and requiring the player to master and possibly memorize many aspects of the game.

Nowadays a player will simply move on to a different game if he failed several times and could not continue from the last checkpoint (see web access) so giving the reigns to the player has become the norm.

# Answer
> 1 votes
tl;dr: Games are getting easier (and casual) and designing games where the player is rewarded (sometimes games where you can't even lose) makes the player more addicted and inclined to reach a wider audience.

One answer that I believe we also have to take into consideration, even though the coin issue of arcade platform makes a lot of sense, was that games used to be much harder.

As Hackworth explained, high difficulty would make player spend more money in the game. For example, Time Crisis or Tekken were designed to make you think you were close to finishing the game, so sometimes one would pay 4 or 5 times to go further into the game.

From a gaming point of view, however, this doesn't make that much sense. What's the point of bringing a "game-over" screen if the player can reload the game for free and try the level again?

Now, the democratization of video gaming also has a role in this issue. Games have gained new target, for instance the older people are an important target of the Wii console. I know I'm not giving any source here, but it is a commonly accepted cliché and a *fact* that video games are becoming easier. The idea of making a game more rewarding has been a current trend for many years; thus, many flash games included a system of badges or requirements to show the player that he was making advance in the game (and that he should continue playing it whereas old games would perhaps have frustrated him).

Many RPG are constructed so that the longer the player is in the game, the better he becomes. I think this might be because of the internet: like TV series, it is a goal to make players stay as long as possible in an online game because of advertisement, which wouldn't be the case with arcade games.

# Answer
> -1 votes
Other answers have already covered the history aspect, e.g, how home gaming learning the wrong thing about the arcades.

In modern games, you generally either give the player a challenge, or you're trying to tell a story. In the 'challenge' category, when you fail, you fail. In the 'story' category, you will want to let the player keep retrying, however badly he plays.

Whenever you get to a situation where multiple lives might be applicable, you have to wonder why you're making them limited.

If you're telling a story, you don't want to have limited lives.. and if you're not and the player is, basically, playing for a high score, something very few games aim for anymore, there are more entertaining ways to practically give the player "more lives". Such as limited amount of shields, plain hit points, etc.

One game I played recently that actually does have limited "lives" is shatter, which is a breakwall game (but the best of that genre I've seen so far); you get a limited number of balls. Once you run out of those, the game does let you continue, but your score resets; so the concept is still out there. I haven't played a lot of shmups lately but I wouldn't be surprised if they still had limited lives.

In the end, it all pretty much boils down to "which option is more fun".

# Answer
> -1 votes
The deprecation of the "many lives" dynamic was based on what was going on in the arcades. Games of the late 70s and early 80s, as you mention, typically had three lives along with the ability to gain extra lives either through scoring a certain number of points or power ups.

For a single quarter, if a player was good enough, he or she could play the arcade game for a very long period of time. I once played the game Cheyenne for two hours at a Nathan's game room out on long island. Similarly, people I know could play "Dig Dug" or "Pacman" for quite a long time as well. - on just one quarter.

Arcade games moved away from this in order to generate more revenue per hour as they lost market share to consoles. A single try followed but "insert another 50 cents to continue" with a counter of 9 seconds became a standard for many arcade games in the late 80s.

http://skillz.com/blog/2013/02/28/how-video-game-business-models-impact-game-design/

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


# Question
Title: How to implement a multi-platform Java 2D game engine's graphics?
I'm not sure whether this question should be posted here. I'm trying to make a basic generic game engine in Java. Here's what I have so far.

```
public abstract class Device {
    public abstract void startDevice();
    public abstract void closeDevice();
    public abstract int getWidth();
    public abstract int getHeight();
    public abstract void displayImage(Image im);
}
public class Game {
    public final Device device;
    public synchronized void gameStart() { ... }
}
public abstract class GameEntity implements Serializable {
    public abstract void create(Game g);
    public abstract void updateAndDraw(Game g, Graphics2D g2d);
    public abstract void destroy(Game g);
}

```

So far, I have implemented two concrete classes for Device, SwingDevice and J2meDevice, and it's working fine. Now the problem is I want to implement AndroidDevice. Everything will work just fine except for that I have enforced using java.awt.Image and java.awt.Graphics2D to paint Game's graphics offline. Then I forward this Image to the device for rendering.

**Is there any way I can absolutely decouple the Device's graphics from the rest of the engine?**

I have two solutions but I doubt they'll fully achieve what I need:

* Stick with the java.awt.Image. Devices that support OpenGL will not fully utilize their hardware capabilities as drawing is done on CPU. And it might not work on platforms on which can't import java.awt (I doubt their existence).
* Create my Graphics2D-like interface. This will make defining new devices harder and again it might hide some of the device's features.

# Answer
Decouple your game domain from the renderer. Then you can implement specific rendering functionality together with your specific device. The Visitor pattern is an excellent candidate for this.

```
class GameEntity {
      public abstract void create(Game g);
      public abstract void update(Game g);
      public void visit(Visitor v) { v.visit(this); }
}

class AndroidRenderer implements Visitor {
      public abstract void visit(GameEntity g) {
          String spriteKey = g.getSprite();
          AndroidAsset sprite = AndroidSpriteStore.getSprite(spriteKey);
          androidCanvas.drawImage(g.getX(), g.getY(), sprite);
      }
}

class AWTRenderer implements Visitor {
      public abstract void visit(GameEntity g) {
          String spriteKey = g.getSprite();
          Image sprite = AWTSpriteStore.getSprite(spriteKey);
          graphics.drawImage(g.getX(), g.getY(), sprite);
      }
}

```
> 2 votes

---
Tags: opengl, java, android, game-loop
---


# Question
Title: Why does my collision implementation cause my player to "bounce" when a collision occurs?
I have a player polygon and I check to see if it's colliding with my tiled map with this method:

```
public static boolean playerCollisionWith() {
    for(int i = 0; i < Blockmap.entities.size(); i++) {
        Block entity1 = (Block) Blockmap.entities.get(i);
        if(playerPoly.intersects(entity1.poly)) {
            return true;
        }
    }
    return false;
}

```

This would work normally but I'm using a different method for movement. Instead of just adding a speed variable to the player's `X` axis. I move like this:

```
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
        speedX = Math.min(5, speedX + 1);
        moving = true;

        playerPoly.setX(x);
        if(playerCollisionWith()) {
            speedX = -5;

            playerPoly.setX(x);
        }
    }

```

That `Math.min` call is what is messing me up. I can't just call `speedX = -5`, because when I do the player "bounces" when the right mouse button is down and it's colliding. Bounces as in flashes back and forth *really* quickly. But I don't really know how I would make it so that collisions on the `Y` axis would work either, whether the player is jumping or not. So if I could get some help with how to fix this problem that would be great.

EDIT: I just realized something, I have these lines of code which I'm pretty sure has a big effect on my collision problems.

```
if(!Keyboard.isKeyDown(Keyboard.KEY_LEFT) && speedX < 0 && !playerCollisionWith()) {
            speedX = 0f;

            playerPoly.setX(x);
        }
        if(!Keyboard.isKeyDown(Keyboard.KEY_RIGHT) && speedX > 0 && !playerCollisionWith()) {
            speedX = 0f;

            playerPoly.setX(x);
        }

```

So when I collide with a wall and I'm no longer pressing the arrow key, than the player drifts into the wall and is all glitchy. Sorry I didn't say that earlier, I just did some more testing. Thanks again!

# Answer
The problem is the `speedX = -5;` assignment in this code:

```
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
    speedX = Math.min(5, speedX + 1);
    moving = true;

    playerPoly.setX(x);
    if(playerCollisionWith()) {
        speedX = -5;  // <---- PROBLEM!

        playerPoly.setX(x);
    }
}

```

In other words, when there's a collision, you set the speed to -5, regardless of which direction the character was going or how fast. If the character was moving forward (positive speedX), it suddenly ricochets backwards. If it was moving backwards at a speed of -4 to -1 inclusive, it suddenly speeds up.
> 1 votes

# Answer
The bouncing happens because you move the Character despite the movement not being valid. In order to prevent it from happening, you should only move the Character after checking if that movement is ok.

```

if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
    if(!playerCollisionWith()) {
        moving = true;
        speedX = 5;
        playerPoly.setX(x);
    }
}

```
> 0 votes

# Answer
Your character is shifting between a speed of +5 and -5 between frames, causing the flashing. I'm not sure what kind of effect you are looking for, so solutions may vary.

Firstly, for input, keep things simple. Modify speed, leave the rest for another function:

```
if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT) {
    speedX = Math.min(5, speedX + 1);
}

```

*(Note: since you are adding 1 to speed every frame, the rate the character accelerates at will be frame rate dependant, meaning it'll only work as expected at a certain fixed frame rate. Fixing it is beyond the scope of this question, but essentially you'd want to make acceleration/speed a function of time, to have your game work at slower or faster frame rates)*

Now you've got your input function. Next, an update function. Here is where you actually move the player, and check for collisions. I haven't programmed in Java for a while, so I apologize for any errors in syntax:

```
public void update() {
    if (speedX > 0.0f) {  // Check if moving right
        positionX += speedX;
        // positionX += speedX * delta; // would produce a better result (where
                                        // delta is the change in time from the
                                        // last frame to this frame)
        float collisionRight = checkCollisionRight(); // This function checks
            // collisions to the right, and returns a value for how much the
            // player is intersection. 0 if not intersecting.

        if (collisionRight > 0.0f) {  // Check if collision, if so, resolve collision
            positionX -= collisionRight; // Just shift the player back by
                                         // the amount intersected
            speedX = 0.0f;  // This stops the player if colliding. If you
                            // want a bounce, the process is more complicated
        }
    }
}

```

Get the idea? Make collision detection and resolution independent of input, to minimize strange behaviour. The above still isn't perfect (what if the player is moving so fast, they end up moving through a wall, for example), but it's a start. If you want to do some reading on collision detection, look up *AABB collision*, it's one of the most basic and effective methods for simple collision detection.
> 0 votes

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


# Question
Title: Screen space decals, converting world to decal space
I'm trying to do screen space deferred decals following the presentation made by Pope Kim about SSDs in WH40K: Space Marine (link). I've gotten to the point where I can render a decal if the bounding box is placed at the world space origin (0, 0, 0). The moment I move the bounding volume the decal is still trying to render at the world space origin and can be seen if you look "through" the bounding volume. The red planes in the picture are the bounding volume rendered for reference, the circular patch is the decal.

Picture showing a decal rendered correctly at world space origin

Picture showing a decal clipped when rendered offset from world space origin

Decal as seen "through" offset bounding volume.

My code is fairly similar to that off Kim, with minor differences accounting for the D3D to OpenGL transition.

Vertex shader:

```
#version 430

layout (shared) uniform PerFrameBlock
{
    mat4 gView;
    mat4 gProjection;
};

uniform mat4 modelMatrix;
uniform vec3 decalSize;

layout ( location = 0 ) in vec4 positionIN;
layout ( location = 1 ) in vec4 normalIN;
layout ( location = 2 ) in vec4 tangentIN;
layout ( location = 3 ) in ivec4 boneIndices;
layout ( location = 4 ) in vec4 boneWeights;
layout ( location = 5 ) in vec2 uvIN;

out vec4 posFS;
out vec4 posW;
out vec2 uvFS;

void main()
{
    posW = modelMatrix * vec4(positionIN.xyz * 1, positionIN.w);
    //Move position to clip space
    posFS = gProjection * gView * posW;
    uvFS = uvIN;
    gl_Position = posFS;
}

```

Fragment shader:

```
#version 430
#extension GL_ARB_texture_rectangle : enable

in vec4 posFS;
in vec4 posW;
in vec2 uvFS;

uniform sampler2D gNormalDepth;
uniform sampler2D gDiffuse;

uniform float gGamma;

uniform mat4 invProjView;
uniform mat4 invModelMatrix;

vec4 reconstruct_pos(float z, vec2 uv_f)
{
    vec4 sPos = vec4(uv_f * 2.0 - 1.0, z, 1.0);
    sPos = invProjView * sPos;
    return vec4((sPos.xyz / sPos.w ), sPos.w);
}

layout ( location = 1 ) out vec4 diffuseRT;
layout ( location = 2 ) out vec4 specularRT;
layout ( location = 3 ) out vec4 glowMatIDRT;

void main()
{
    vec2 screenPosition = posFS.xy / posFS.w;

    vec2 depthUV = screenPosition * 0.5f + 0.5f;
    depthUV += vec2(0.5f / 1280.0f, 0.5f / 720.0f); //half pixel offset
    float depth = texture2D(gNormalDepth, depthUV).w;

    vec4 worldPos = reconstruct_pos(depth, depthUV);
    vec4 localPos = invModelMatrix * worldPos;

    float dist = 0.5f - abs(localPos.y);
    float dist2 = 0.5f - abs(localPos.x);

    if (dist > 0.0f && dist2 > 0)
    {
        vec2 uv = vec2(localPos.x, localPos.y) + 0.5f;
        vec4 diffuseColor = texture2D(gDiffuse, uv);
        diffuseRT = diffuseColor;
    }
    else
        diffuseRT = vec4(1.0f, 0, 0, 1);
}

```

I think my problem stems from the conversion from world space to decal space using the inverse model matrix. The model matrix is build by the following code:

```
        glm::quat rot;
glm::mat4 rotationMatrix;
glm::mat4 translationMatrix;
glm::mat4 scaleMatrix;

        rotationMatrix = glm::toMat4(rotation);
        translationMatrix = glm::translate(glm::mat4(1.0f), position);
        scaleMatrix = glm::scale(scaleX, scaleY, scaleZ);

       modelMatrix = translationMatrix * rotationMatrix * scaleMatrix;

```

To get the inverse I just use the following:

```
glm::inverse(modelMatrix)

```

What I'm wondering is if inverting the model matrix like this actually correct or am I doing something with it which would cause this kind of behaviour? I've tried offsetting the calculated local space position in the shader with no luck (probably because the distance gets borked) and I'm starting to run out of ideas.

Any help is much appreciated!

# Answer
It looks like the translation component of your inverse model matrix is being ignored. Can you confirm this by trying it with a rotated/scaled model?

(If nothing changes at all, it could be a sign that the inverse model matrix isn't being passed to the shader correctly, and so it's always using an identity matrix with no translation)

If it is indeed selective to translation, and scale/rotation come through as expected, then suspect #1 is your w component. Try manually setting worldPos.w = 1.0f; before multiplying by the inverse model matrix, to ensure the translation isn't being zeroed-out.

I implemented one of these myself recently in Unity, and the rest of your code looks correct to my eye, but I'm not super fluent in native OpenGL.
> 1 votes

---
Tags: opengl, matrix, deferred-rendering, deferred-shading, decal-system
---


# Question
Title: Why are there lines in between my tiles?
I'm making a top down XNA game. The maps are created by tiles. A problem I recently noticed is a 'grid' of lines between the tiles. It only shows up sometimes and only depending on the camera position. I let XNA handle the positioning, why are these lines showing up?

Here is a picture with the lines:

However, after moving my camera over just a bit, it magically goes back to how it is supposed to appear:

Thanks for any help!

**EDIT:**

This is the best I can do for source code, this is an extremely large project and the rendering is done it multiple areas:

**Main Render Loop** *For dynamic elements such as tiles:*

```
    spriteBatch.Begin(SpriteSortMode.Deferred, Nothing, SamplerState.LinearClamp, Nothing, Nothing, Nothing, Matrix.CreateTranslation(CameraX, CameraY, 0))
    Mode.Render(spriteBatch, False)
    For Each j As [Delegate] In DynamicInjectionList
        j.DynamicInvoke(spriteBatch)
    Next
    DynamicInjectionList.Clear()
    spriteBatch.End()

```

**`Mode.Render`:**

```
For x As Integer = 0 To GRIDMAX - 1
    For y As Integer = 0 To GRIDMAX - 1
        For z As Integer = 0 To 2
            Dim ter As TiledTerrain = Terrain(x, y, z)
            If ter IsNot Nothing Then
                sb.Draw(CBaseClient.TextureLibrary("TileMap"), New Rectangle(x * GRIDSIZE, y * GRIDSIZE, GRIDSIZE, GRIDSIZE), New Rectangle(ter.Texture_X, ter.Texture_Y, GRIDSIZE, GRIDSIZE), Color.White)
            End If
        Next
    Next
Next

```

**`TiledTerrain.vb` Class:**

```
Imports ProtoBuf

<ProtoContract()> _
Public Class TiledTerrain

    <ProtoMember(1)> _
    Public Property X As Integer
    <ProtoMember(2)> _
    Public Property Y As Integer
    <ProtoMember(3)> _
    Public Property Z As Integer

    <ProtoMember(4)> _
    Public Property Texture_X As Integer
    <ProtoMember(5)> _
    Public Property Texture_Y As Integer

End Class

```

**My Research:**

I've done some searching into it and this is was I've found:

* This problem is called tearing (I believe?)
* It is commonly caused by using a floating point data type to hold the tile position (I'm using `Integer` so this shouldn't be a problem right?)

# Answer
I assume that although your tile positions are defined in integers, your camera position may not be. So if you are trying to render pixel-perfect positions from a *non*-pixel-perfect position then the sampling may be off and cause lines between the tiles. In your `SpriteBatch.Draw` calls, I would suggesting changing the SamplerState to `PointClamp` to ensure that the textures are sampled on a point basis and it should remove those extra lines.

Your code revised:

```
spriteBatch.Begin(
    SpriteSortMode.Deferred,
    Nothing,
    SamplerState.PointClamp,
    Nothing,
    Nothing,
    Nothing,
    Matrix.CreateTranslation(CameraX, CameraY, 0))

```
> 20 votes

# Answer
I had a similar problem with DirectX 11 and this worked for me:

I changed the texture address mode in the sampler state description. Texture address mode is used to control what Direct3D does with texture coordinates outside of the range (in DirectX 11, this is `[0.0f, 1.0f]`). I changed the `ADDRESS_U`, `ADDRESS_V`, `ADDRESS_W` members to `D3D11_TEXTURE_ADDRESS_CLAMP` which clamps out-of-range values of texture coordinates into the range.

If there is an analogous parameter in your code than this might help.
> 1 votes

# Answer
I had a similar problem with lines showing up between my tiles too, but changing the sampler state to Point Clamp did not fix the problem.

Instead I found that turning off multi-sampling and synchronizing the vertical trace fixed the problem. This is in XNA 4.0:

```
public GraphicsDeviceManager _graphics;

_graphics = new GraphicsDeviceManager(this);
_graphics.PreferMultiSampling = false;
_graphics.SynchronizeWithVerticalRetrace = true;

```

Hope this helps someone out there!
> 0 votes

---
Tags: xna-4.0, tiles, terrain-rendering
---


# Question
Title: How should I design my classes in a game?
I'm stuck for ideas on classes in game programming. This is probably more of an opinion based question. I'm looking for information that is proving hard to find on the internet.

Say I have a class called `Bullet` or `Mob`, the name doesn't really matter it's just an example. With this, there are two options I can think of.

1. Have the class purely as a way of storing data and nothing else. So I could have, for example, properties such as `EntityID`, `Velocity`, `HealthPoints`, `NumberOfAttacks`. I would then have some other part of the game which iterates through every instance of every object and update the properties from there.

Example: During the iteration, it checks what type of object it is, such as `Bullet` etc. Once it has checked this, it will calculate where the bullet should move to next based upon the `Velocity` property.
2. Or, have the same properties within the class, but also have all the code for updating it's own properties in there too. Example: The bullet has some kind of `Update()` method which get's called periodically by the game engine. This `Update` method would then take it upon itself to calculate the new `Velocity` and update it's position etc.
3. Some combination of the both? Something else I haven't thought of?

Which of these options is the more commonly used approach in game programming? What are the benefits or disadvantages of these different methods?

Have I got it all completely wrong?

# Answer
> 5 votes
Keep `Bullet` functionality in the `Bullet` class.

This just sounded like nails against a chalkboard to me:

> During the iteration, it checks what type of object it is, such as `Bullet` etc. Once it has checked this, it will calculate where the bullet should move to next based upon the `Velocity` property.

*Aaagh.* D:

It's not the base `Entity` class' responsibility to check if it's a `Bullet` -- that's what method overriding is for!

I like to do this (and I know many other developers who do):

Have a base `Entity` class that defines properties like `speed`, `position` and `id` that all entities will need anyway, along with an `Update(dt)` method that computes its position in the next step. All entities (such as `Bullet` or `Player`) then inherit from `Entity`. If necessary, they override `Update(dt)` to add functionality such as consider keyboard input or resolve collisions, then probably call `super` to do the actual movement, so there's no code duplication.

Your *Method 2* sounds just like this. I'd go with that.

*Whether each entity should render itself or whether rendering should be done globally* is a related consideration that has been discussed at length. The answers there might be helpful too.

# Answer
> 1 votes
In my case, I went about a lot of this through composition (more precisely through the Strategy Pattern). I built an interface, and made LinearMovement and CircularMovement classes. My friend later added a ParabolicMovement class. Any of these can be provided to a game object at will; you can swap them out at any time. The result is that the function that does the moving changes, and may have different values for speed, acceleration, angle, etc without requiring a separate concrete class.

We aren't very far along, but the flexibility of this approach is very noticeable. Done right, a player character could be of the same type as a bullet, but with different values. Going that far may not be worth it, depending on your situation, but it should be worth considering. That it helps with movement, I have no doubt. Note that the properties you've mentioned often get split off between the strategy classes in this case.

---
Tags: c#, design-patterns, objects
---


title: LibGdx Android Phone Resolution problem

text:
# Question
Title: LibGdx Android Phone Resolution problem
I am using the LibGdx framework and have an issue.

Currently, I am creating a game in a resolution of 480 x 320 and using 'GL20' to remove the restriction of that dreaded 'power of two' error.

It works really well, but only in desktop and phones whose screen sizes are the same. But when I try it to a phone with a resolution of 320 x 240, I can only see a small part of the screen and the screen calculations that I made for touch events are now incorrect.

Is there any way to make it work the same as in the desktop version? Like for example, even on the 320x240 phone, the resolution of the game is still at 480x320.

# Answer
This is a problem pretty much everyone faces when getting into LibGDX. What you need to remember as you code is this: pixels are bad. Down with pixels.

Because you're using a camera object to determine how/where to draw your sprites on screen, you can set your game's world to use any units you want, and scale to each screen just by constructing the camera appropriately.

If you were to use a tile map to build your levels, I'd say use those tiles as your unit. Doesn't matter how you draw your levels, though -- make up a unit of measurement and stick to it. My screen (in landscape view) is 20 units (tiles, metres, character-heights, whatever) high, with the width scaled so that the tiles are square (ppu is pixels per unit):

```
// Always a screen height of 20 units;
// width depends on screen aspect ratio.
float height = 20;
float ppu = Gdx.graphics.getHeight() / height;
float width = Gdx.graphics.getWidth() / ppu;

```

So say you run it on a Full HD screen (1920x1080). If `height = 20`, then `ppu = (1080 / 20) = 54`. So `width = (1920 / 54) = 35.55555...` Your sprites will be automatically scaled (up) to fit that screen size.

On the smaller of the resolutions you mentioned? `ppu = (240 / 20) = 12`, so `width = (320 / 12) = 26.66666...` Your sprites will be automatically scaled (down, this time) to fit that screen too.

Then construct your camera using those values:

```
OrthographicCamera cam = new OrthographicCamera(width, height);
cam.position.set(width / 2, height / 2, 0);
cam.update();

```

`width / 2` and `height / 2` being the centre of the screen. If you're using your camera's combined matrix as the `SpriteBatch`'s projection matrix -- `batch.setProjectionMatrix(cam.combined)` -- then it'll take care of screen resolution for you. And that's it.

Well, almost. You now need to define your Sprites and any other objects in your shiny new world coordinates. If your Sprite was 32 pixels high on your test 480x320 phone, its new height is 2. *Don't* change the TextureRegions -- they're still in pixels, since they're to do with your image file, not your world. Not at all confusing, right?

Now, if you want to translate from touch coordinates to in-game coordinates, you need to do a two-step conversion as explained here. First from screen coords to camera coords, then from camera coords to world coords:

```
// Vector2 touchV comes from your InputAdapter.touchDown()
cam.unproject(touchV);
float x = cam.position.x - cam.viewportWidth + touchV.x;
float y = cam.position.y - cam.viewportHeight + touchV.y;

```
> 12 votes

---
Tags: android, libgdx
---