# Question
Title: How do I create an actor class in UDK that will spawn a specific particle system?
I'm trying to write a new class that I can drag from actor classes window into the scene and it will spawn a specific particle effect. Its going to be a 'prop' that later will also contain a static mesh and a point light. Maybe some defined variables that can be changed in the properties window. So far, I have the static mesh working using this code:

```
class LightFixture extends StaticMeshActor;

defaultproperties
{
    Begin Object Class=StaticMeshComponent Name=myMesh
        bAllowApproximateOcclusion=TRUE
        bForceDirectLightMap=TRUE
        bUsePrecomputedShadows=TRUE
        StaticMesh=StaticMesh'props.Meshes.lamp'
    End Object

    Components.Add(myMesh)
}

```

now, I'd like to add a particle system (template?), and from what I'm learning, it's not as easy as adding the mesh. In a new class, I tried to add a particle effect this way:

```
class FireParticle extends EmitterPool
placeable;

var ParticleSystemComponent PSC;

defaultproperties
{
    Begin Object Class=ParticleSystemComponent Name=myEffect
        bAutoActivate=true
        Template=ParticleSystem'props.FX.fire'
    End Object

    ParticleSystemComponent=myEffect
    Components.Add(myEffect)
}

```

So that didn't work... I read somewhere that emitterpool was the way to spawn.. I am very new to scripting, if that isn't already obvious :)

thanks in advance, if anyone can help..

# Answer
> 1 votes
The EmitterPool is a manager class that you can use to spawn temporary emitters. You would do this by calling `WorldInfo.MyEmitterPool.SpawnEmitter(...)`. For permanent emitters, you just need a ParticleSystemComponent variable in your actor set up basically exactly like you're doing.

So the main problem is that EmitterPool is defined in such a way that you can't place it (or subclasses of it) within the editor. You need to make your FireParticle class derive directly from Actor. Secondly, you need to change `ParticleSystemComponent=myEffect` to `PSC=myEffect`, so you assign it to your variable. With those two changes, you should be good to go.

# Answer
> 0 votes
Create a class something like this:

```
class MyParticleActor extends Actor placeable;

var ParticleSystemComponent ThePausePSC;

simulated event PostBeginPlay(){
    super.PostBeginPlay();
    ActivateMyPSC();
}

simulated function ActivateMyPSC(){
    if(ThePausePSC != none){
        ThePausePSC.SetScale(20.f);
        ThePausePSC.CustomTimeDilation = 0.25f;
        ThePausePSC.ActivateSystem();
    }
}

simulated function DeactivateMyPSC(){
    if(ThePausePSC != none){
        ThePausePSC.DeactivateSystem();
    }
}

defaultproperties
{
    Begin Object Class=ParticleSystemComponent Name=ThePauseParticleEffectSystemComponent
        Template=ParticleSystem'Eagle.Effects.PE_RobotPause';
        bAutoActivate=false
        bOwnerNoSee=true
        Scale=10.f
        Translation=(X=0.f,Y=0.f,Z=0.f)
    End Object
    ThePausePSC=ThePauseParticleEffectSystemComponent
    Components.add(ThePauseParticleEffectSystemComponent)

    Begin Object Class=SpriteComponent Name=Sprite44
        Sprite=Texture2D'EditorResources.Crowd.T_Crowd_Destination'
        HiddenGame=true
        HiddenEditor=false
        AlwaysLoadOnClient=False
        AlwaysLoadOnServer=False
        SpriteCategoryName="GSD"
        Scale=1
    End Object
    Components.Add(Sprite44)
}

```

Then drag and place on level. Right click on actor in level and click create archtype.

Find arch type in content browser, position viewport to get a good view of the particle effect in action, and right click on the arch type in content browser and set thumbnail to active viewport. Now you can drag it from the content browser.

What Philip says is correct as well, pay attention when to use the emitter pool and when not to depending on your usage of the particle.

---
Tags: udk, scripting, particles
---


title: Collision detection tutorials

text:
# Question
Title: Collision detection tutorials
I'm supposed to develop a Java game using AWT and Applet libraries. I'm stuck with the concept of "collision detection". If you can help me with any tutorials that explain the concept (how it works) or give examples (source code), I'd be grateful.

# Answer
> 1 votes
It depends on what you're trying to do, but I'll just keep it simple.

This tutorial explains basic forms of collision detection. They're formatted for AS3, but the concepts behind them can be used for any language.

---
Tags: java, collision-detection, game-mechanics
---


title: UDK : Problem with Touching Actors

text:
# Question
Title: UDK : Problem with Touching Actors
In my game I am trying to see all touching actors of a particular DynamicSMActor and it does return only two Actors as touching Actors - Water Volume and Player Pawn. It is ignoring all the other DynamicSMActors that are touching. I actually tried different values for collision type, Blocking type, etc,. No success.

Any help is really appreciated.

# Answer
> 1 votes
Verify that the objects are actually touching (colliding) and not just passing through. You can do this by logging the touch and untouch events in unrealscript or via kismet. If they are passing through without touch firing, the collision properties of one or more of the actors needs adjusted accordingly to allow collision with each other.

In unrealscript, Actor:

* event Touch( Actor Other, PrimitiveComponent OtherComp, vector HitLocation, vector HitNormal );
* event PostTouch( Actor Other ); // called for PendingTouch actor after physics completes
* event UnTouch( Actor Other );

In kismet, new event -\> physics -\> touch.

---
Tags: udk, unreal
---


# Question
Title: vec4 for vec3 multiplication while calculating the specular value
I'm following this tutorial to calculate the specular color of a vertex.

I use OpenGL 2.1 with GLSL version 120.

This is the formula that I apply:

> spec= (R\*eye)^s * Ls * Lm

With:

> L= direction vector light-vertex;
> N= vector normal;
> eye= direction vector vertex-eye;
> R= -2N * (L\*N) + L;

Now the problem is that following this way I need to multiply a vec3 for a vec4.

This is what I tried to do:

```
vec4 L= normalize(gl_LightSource[0].position - gl_Position);
vec3 N= normalize (gl_NormalMatrix * gl_Normal);
vec4 eye= normalize(-gl_Position);
vec4 R= -2.0*N*(L*N)+L;  // Syntax error: N is a vec3
vec4 spec= (R*eye)* gl_LightSource[0].specular;

```

I wouldn't get a vec3 result when calculating the specular value, this value I would be ignoring the alpha value. How do I go around this?

# Answer
It needs to be a `vec3` because the 4th component of the homogeneous coordinates is only used for 3D transformations. If you use them for *eg.* dot products, they will likely pollute the final result.

Speaking of dot products, `R*eye` is most probably wrong; you want `dot(R,eye)` instead.

Also, the dot product should be saturated to avoid negative values.

This code should work better:

```
vec3 L = normalize(gl_LightSource[0].position.xyz - gl_Position.xyz);
vec3 N = normalize((gl_NormalMatrix * gl_Normal).xyz);
vec3 eye = normalize(-gl_Position.xyz);
vec3 R = -2.0 * N * max(dot(L, N), 0.0) + L;
vec3 spec = max(dot(R, eye), 0.0) * gl_LightSource[0].specular.rgb;

```

Finally, the specular power (sometimes called `shininess`) should be applied to `dot(R, eye)` before being multiplied by the specular colour, so something like this:

```
vec3 spec = pow(max(dot(R, eye), 0.0), shininess)
          * gl_LightSource[0].specular.rgb;

```
> 2 votes

---
Tags: opengl, glsl, lighting
---


title: Who should manage projectiles?

text:
# Question
Title: Who should manage projectiles?
I was following a tutorial that was recommended to me to learn the basics of game design through XNA. And I got to this tutorial: http://www.xnadevelopment.com/tutorials/thewizardshooting/thewizardshooting.shtml

This is the tutorial that shows management of dynamic object generation and handling.

In the tutorial, he links the "Fireball" class to the "Wizard" class. The wizard class maintains a `List<Fireball>` and they're updated, drawn, loaded, etc. within the Wizard class itself.

My question is this: Is this good design? Should the Producer of the Objects be the one to manage them, or would it be better to implement, say, a `ProjectileHandler` class, that could manage the fireballs shot both by the `Wizard` and the `Evil Dragon`?

# Answer
Treat projectiles as particles and use a kind of particle system to manage them. In essence you know you want to control where the projectiles spawn, and how long/where they are deleted, but moving the projectiles should be automated.

Instead of the Fireball class extending the Sprite class (which to me already sounds like a bad design), have the ProjectileHandler class with a list of Fireball objects, each including a Sprite. Fireball objects define a direction, which the ProjectileHandler uses to update the position. This way you can spawn a new Fireball with any sprite you want like: `ProjectileHandler.AddProjectile (new Fireball(sprite, position, direction));` and the FireballManager adds it to the list.

You may notice that the Sprite could be just about anything here, so Fireball can be just as well be given a more generic name to suit all kinds of projectiles. The ProjectileHandler is unaware of what texture each projectile uses for the sprite. The dragon may use different, bigger fireball sprites, or you may want the wizard to upgrade his attacks and have the new fireballs look the part.

Byte56 did mention that texture switching should be kept to a minimum, so this implementation has that drawback of not doing so automatically as different sprites can be added in any order. I suppose a sorted List of `KeyValuePair<Sprite, Fireball>` would solve this, but don't try to optimize yet unless it becomes real necessary.

The reason I said it's bad to have Fireball to extend from Sprite is that Fireball is treated as a projectile, not a Sprite. It should instead *contain* a Sprite object to represent that Fireball visually.
> 2 votes

# Answer
For me, projectiles are just another kind of object in the game. They don't need a separate manager, and just get updated along with every other updateable object such as characters. It is sometimes useful for them to keep a reference to their creator however (eg. for deciding who was responsible for inflicting damage).
> 3 votes

# Answer
If the current scenario works, you don't need to change it.

However, I can see some benefits of having a projectile handler. You would need to make a change to the `Fireball` class to include a reference to the owner though. One nice thing about the `Wizard` class managing all his projectiles is you know which ones are his, and can easily emulate that with a reference to the owner in the `Fireball`.

Keeping all the projectiles in a single class can mean a few things. For one, you have far more control over the order these things get drawn instead of having each "producer" manage their own projectiles. Given that, there are some rendering improvements you can make based on knowing *when* these objects will be drawn. You can load the fireball texture once, then draw *all* the fireballs in the scene, for example. That cuts down on texture switching. Having all the projectiles in one place makes it easier to implement things like projectile-projectile collision.
> 1 votes

# Answer
A good reason for having the fireballs in a list of projectiles rather than owned by the wizard is what happens when the wizard dies? Do you want his fireballs in flight to suddenly vanish?
> 0 votes

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


title: logitech dual shock Python support

text:
# Question
Title: logitech dual shock Python support
Does anyone know how to use "dual vibration feedback makes your games more realistic and immersive." on this logitech gamepad

I know about pygame however I don't think it gives feedback.

http://www.logitech.com/en-us/product/wireless-gamepad-f710

# Answer
> 1 votes
Assuming this is on Windows you'll probably want to use DirectInput either via a Python wrapper if you can find / write one, or by using another programming language like C++ or C#.

A quick search suggests pyglet has at least some DirectInput support, but I don't know if that includes force feedback.

---
Tags: gamepad
---


# Question
Title: Automatic Tile Transitions Not Working Correctly
I've started writing a tile based game in XNA today using the tutorials here. I'm on the Part 6 - Side Topic - Auto Transitions at the moment. My transitions aren't working correctly as you can see below:

When moving around, several of the tiles don't transitions correctly and stay as the default square, you can see this happening with the 2 bottom right 'water' tiles, they're not transitioning with the 'dark grass' tiles.

Here's the class that does the transitioning:

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

namespace WindowsGame1
{
    class TileMap
    {
    public List<MapRow> Rows = new List<MapRow>();
    public int MapWidth = 32;
    public int MapHeight = 32;

    public TileMap()
    {
        for (int y = 0; y < MapHeight; y++)
        {
            MapRow thisRow = new MapRow();
            for (int x = 0; x < MapWidth; x++)
            {
                thisRow.Columns.Add(new MapCell(64));
            }
            Rows.Add(thisRow);
        }

        Rows[0].Columns[3].TileID = 96;
        Rows[0].Columns[4].TileID = 96;
        Rows[0].Columns[5].TileID = 32;
        Rows[0].Columns[6].TileID = 32;
        Rows[0].Columns[7].TileID = 32;

        Rows[1].Columns[3].TileID = 96;
        Rows[1].Columns[4].TileID = 32;
        Rows[1].Columns[5].TileID = 32;
        Rows[1].Columns[6].TileID = 32;
        Rows[1].Columns[7].TileID = 32;

        Rows[2].Columns[2].TileID = 96;
        Rows[2].Columns[3].TileID = 32;
        Rows[2].Columns[4].TileID = 32;
        Rows[2].Columns[5].TileID = 32;
        Rows[2].Columns[6].TileID = 32;
        Rows[2].Columns[7].TileID = 32;

        Rows[3].Columns[2].TileID = 96;
        Rows[3].Columns[3].TileID = 32;
        Rows[3].Columns[4].TileID = 32;
        Rows[3].Columns[5].TileID = 0;
        Rows[3].Columns[6].TileID = 0;
        Rows[3].Columns[7].TileID = 0;

        Rows[4].Columns[2].TileID = 96;
        Rows[4].Columns[3].TileID = 32;
        Rows[4].Columns[4].TileID = 32;
        Rows[4].Columns[5].TileID = 0;
        Rows[4].Columns[6].TileID = 0;
        Rows[4].Columns[7].TileID = 0;

        Rows[5].Columns[2].TileID = 96;
        Rows[5].Columns[3].TileID = 32;
        Rows[5].Columns[4].TileID = 32;
        Rows[5].Columns[5].TileID = 0;
        Rows[5].Columns[6].TileID = 0;
        Rows[5].Columns[7].TileID = 0;

        doAutoTransition();
    }

    private void doAutoTransition()
    {
        for (int y = 0; y < MapHeight; y++)
        {
            for (int x = 0; x < MapWidth; x++)
            {
                int height = getBaseTile(y, x);
                int start = GetTileBaseHeight(height) + 1;
                for (int i = start; i < 4; i++)
                {

                    int tileID = CalculateTransistionTileEdge(y, x, i);
                    if (tileID > -1)
                    {
                        Rows[y].Columns[x].AddBaseTile(i * 32 + tileID);
                    }

                    tileID = CalculateTransistionTileCorner(y, x, i);
                    if (tileID > -1)
                    {
                        Rows[y].Columns[x].AddBaseTile(i * 32 + 16 + tileID);
                    }
                }
            }
        }
    }

    private int GetTileBaseHeight(int tileID)
    {
        return tileID / 32;
    }

    private int getBaseTile(int y, int x)
    {
        if (x < 0 || y < 0 ||
            x >= MapWidth || y >= MapHeight)
        {
            return 0;
        }

        return Rows[y].Columns[x].TileID;
    }

    private int CalculateTransistionTileEdge(int y, int x, int iHeight)
    {
        int temp = 0;

        if (GetTileBaseHeight(getBaseTile(y, x - 1)) == iHeight)
        {
            //Left
            temp += 1;
        }

        if (GetTileBaseHeight(getBaseTile(y - 1, x)) == iHeight)
        {
            //Top
            temp += 2;
        }

        if (GetTileBaseHeight(getBaseTile(y, x + 1)) == iHeight)
        {
            //Right
            temp += 4;
        }
        if (GetTileBaseHeight(getBaseTile(y + 1, x)) == iHeight)
        {
            //bottom
            temp += 8;
        }

        if (temp > 0)
        {
            return temp;
        }

        return -1;
    }

    private int CalculateTransistionTileCorner(int y, int x, int iHeight)
    {
        int temp = 0;

        if (GetTileBaseHeight(getBaseTile(y - 1, x - 1)) == iHeight)
        {
            //Left top
            temp += 1;
        }
        if (GetTileBaseHeight(getBaseTile(y - 1, x + 1)) == iHeight)
        {
            //Top right
            temp += 2;
        }
        if (GetTileBaseHeight(getBaseTile(y + 1, x + 1)) == iHeight)
        {
            //Bottem Right
            temp += 4;
        }
        if (GetTileBaseHeight(getBaseTile(y + 1, x - 1)) == iHeight)
        {
            //Bottom left
            temp += 8;
        }
        if (temp > 0)
        {
            return temp;
        }

        return -1;
    }
}

class MapRow
{
    public List<MapCell> Columns = new List<MapCell>();
   }
}

```

# Answer
Turns out I had the wrong `SpriteSortMode` when drawing the tiles to the screen. Changed it to `SpriteSortMode.Immediate` and works correctly now.
> 0 votes

---
Tags: xna, c#, tiles
---


# Question
Title: What book/guide should I follow for GLSL
I searched a lot on the web without coming to a real solution and if I ask this it's because I really have difficulties getting an answer. I need to learn well GLSL 1.20 with OpenGL 2.1.

I have bought beginning OpenGL game programming, 2nd edition, but it talk too little about GLSL. So I'm following some tutorials like this one, but it just makes a lot of examples without explaining the theory.

The problem is that if I want to know something, I have to search a lot, and often the thing that I'm searching doesn't come straightforward. For example I didn't know how to compute the direction between two points, I looked into some example codes and I discovered that it was done with the dot product just by seeing the example code. But with this approach I waste a lot of time. I need a book/guide which tells me how to do basilar stuff and also explains the theory. I just feel like I'm travelling into the fog. What book/guide would you suggest?

# Answer
The standard reference for GLSL would be referred to as the orange book. Located here on amazon.

http://www.amazon.com/OpenGL-Shading-Language-3rd-Edition/dp/0321637631/ref=pd\_bxgy\_b\_text\_y

*edit* geeze i'm out of it today. Here is the link to the correct book.
> 1 votes

---
Tags: opengl, glsl
---


title: 3d to 2d Collision

text:
# Question
Title: 3d to 2d Collision
I have a 3d model which rotates around my screen, it's always on the Z axis = 0 where everything of my 2d images are. My 2d images fly out of the center and get bigger to give the view as getting closer. I'm trying to detect a collision so I can disable my 2d images to load new ones into the game.

My collision detection isn't working at all and I'm wondering if anyone can shed any light on this.

```
foreach (coins coin in coins)
        {
            coin.Update(_graphics.GraphicsDevice);

            if ((coin.getCoinXPosition() + scale < getModelXPosition() - scale) &&
                (coin.getCoinXPosition() - scale > getModelXPosition() + scale) &&
                (coin.getCoinYPosition() + scale < getModelYPosition() - scale) &&
                (coin.getCoinYPosition() - scale > getModelYPosition() + scale))
            {
                coin.coinVisible = false;
                score++;
                //coins.Remove(coin);
            }

        }

```

# Answer
> 1 votes
Use a BoundingBox structure that the XNA framework will provide you with - in this case you can find the documentation just right here. Simply create a box for all your stuff; with the Z-axis set to 0 accordingly and use the Intersects method to test. Hope this helps!

# Answer
> 0 votes
Another option is to project the 3D model into the target plane and then find the bounding edges (all outer edges) of the result. From this you can find a hull to build a set of convex polygonal shapes via ear clipping for a "real" physics engine like Box2D or Chipmunk or so on.

More complex by far but more accurate, if that matters to you at all.

If you just want the bounding box, you can find that by projecting the model's vertices or projecting its existing object-aligned bounding box, if you don't have an existing 3D AABB.

Converting a 3D AABB to 2D is pretty easy, and basically boils down to tossing out the off-plane coordinates and converting the correct on-plane coordinates to simple X,Y and width,height values (or min/max X,Y values if you use those for your AABBs).

---
Tags: c#, collision-detection, xna-4.0, 2.5d
---


# Question
Title: How well do functional languages perform on Android?
This is a special case of this question that I feel is particularly pertinent.

I'm working on a game for Android, and I'm planning on using Scala with libgdx. I'm planning on making a performant game, but not necessarily hyper-performant game. I saw libgdx's documentation on Garbage Collection, and this makes me think:

1. Functional programming implies lots of immutable objects.
2. Therefore, mutating an object requires making a new object.
3. Thus, lots of objects get garbage collected, which degrades performance.

Is this an insurmountable problem? Are there any other significant problems with functional style on Android?

# Answer
> 3 votes
You can be fine with Scala, but you really do not want to allocate new objects *too frequently*. GC without pauses are still no more that a myth (on Android), and gamers don't like when your game glitches. But this doesn't mean that you cannot take any benefit from using more serious language - indeed, you can. And you'll be OK with "functional style" that doesn't take place in the main game loop. Also, Scala on Android itself requires to fight with some extra build problems, but once you learn it, it's bearable. And it's not very precise to name Scala a functional language, it have some features related to functional programming, though.

# Answer
> 2 votes
For gaming? Avoid functional languages. Their entire paradigm fails to mesh well with games. Procedural, OOP languages better fit with games' needs for frequent state changes, explicit memory and resource management, abstraction of data and model useful in many places, data-oriented design in some systems, and so on. Functional *elements* are one thing, a true functional language is another.

The best performing functional language for Android will still give a worse development experience than Java or C++. Not because those are better languages all around, but because they're better for the specific task at hand. Right tool for the job and all that.

This is true on mobile, PC, consoles, and so on. Nobody uses functional languages for games. Naughty Dog uses LISP for *scripting*, but not the core game code. They can't. It wouldn't work if they tried.

The closest most people get are shaders, which are functional in some ways but written in highly procedural languages like HLSL or GLSL.

---
Tags: java, android, libgdx
---


title: Replacement for XNA?

text:
# Question
Title: Replacement for XNA?
Since Microsoft stopped developing XNA I'm wondering what will be the replacement for the XBox 720°. I've been wondering about this. XNA was THE technologie the XBox, easy and powerfull.

So is Microsoft developing a new technologie or are they going to continue XNA, even if they've said they'd stop.

# Answer
Nobody knows what they have planned as far as indie games are going. Neither do I think XNA will ever be on the Xbox 720. The thing is that it might now be easy for Microsoft to manage developers they never met in person. I would say they might come up with something although there are still arcade games which if your willing to official publish your game you might be able to post it as an arcade game.
> 1 votes

---
Tags: xna, c#, xbox, microsoft
---


title: Any book about math in game design?

text:
# Question
Title: Any book about math in game design?
Game designers need math as one of their tools for designing game, unfortunately I can't find one book concentrate on this topic. I know there's math book about game programmer, but designer need different math sub-branch knowledge like probability, game theory etc. And most important is examples tell us how to use these math knowledge as our powerful tools. Is there some books or articles available talk about this topic? Thanks in advance.

# Answer
> 1 votes
Here's a really helpful wiki: http://math2033.uark.edu/wiki/index.php/Game\_Theory.

I haven't read this, but it looks promising: http://www.goodreads.com/book/show/229281.Game\_Theory

A lot of colleges offer free online course material. Here's one from Yale.

---
Tags: game-design, mathematics, books
---


title: Test for the presence of the ouya ODK

text:
# Question
Title: Test for the presence of the ouya ODK
How would it be possible to test for the presence of the ODK at run time? Currently I took this approach:

```
private activityDelegate delegate;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Need to test for the presence of the ouya ODK here
    {
        delegate = new OuyaDelegate(savedInstanceState);
    }
}

```

But maybe there is a better way of doing this than in the main activity?

# Answer
The standard way of doing this is to pick a class that you know should exist and then see whether it does:

```
try{
    Class.forName("tv.ouya.console.api.OuyaFacade");
} catch (ClassNotFoundException e){
    Log.e(TAG, "No ODK Found!");
}

```
> 3 votes

---
Tags: java, android, ouya
---


# Question
Title: Game maps with "counties" that are split along lines that aren't necessarily straight
I want to create a game environment that supports a 2D map. This is a really basic map, but must be split along lines that are not necessarily straight. So imagine a country with county boundaries. I then want to be able to detect drag / drop events within these counties.

What I'm really looking for here is a pointer to where to start on this (how it has been done before - any existing libraries out there), as I'm sure that what I'm trying to do is not new - although I can't find a beginners guide for this anywhere.

# Answer
> 7 votes
There are two general approaches I would take.

1) The polygon-based approach. Each of your zones is defined as a series of points. You can then do point-in-polygon testing for whether or not your cursor position is inside a given area. You can also do things like tessellate it and draw an image on it.

2) The image-based approach. Author an image where a specific pixel color represents a certain area. Kind of like how this question does. Then you do a check in the image pixel data for what color you're currently selecting to determine which zone you're in.

# Answer
> 1 votes
Amit Patel has some great information on polygonal map generation here: http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/

He uses random points and generates a Voronoi diagram from those, and from there you can coalesce adjacent polygons to form county boundaries. Each of the original polygons is convex so checking a mouse click within them is fairly simple.

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


title: TiledMaps and real objects

text:
# Question
Title: TiledMaps and real objects
I'm creating a simple game for the iPhone using Cocos2d. I'm having a hard time understanding how add real objects to a tiled map.

I know that you can add an object-layer to the tiled map and set the position of it, but I'm not sure how to define WHAT object it should be.

For example, if I'm creating a simple Super Mario Bros. I want to add different blocks to the map, one should hold a star, one should hold a coin, and so on.

How should I define what object it is?

So my question, how do I correctly create class-objects in a tiled map?

# Answer
First, you should have a top layer in your tiled map. This layer will have the same amount of tiles (x, y) as the rest of your map and should be rendered last. In my game, I created a placeEntity(Entity e, int xTile, int yTile) method so you can add the gameplay objects anywhere you want in the map.

About the Stars and Coins, they're just the Star and Coin objects placed at an x and y position using the above method.
> 1 votes

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


title: ResourceContentManager with folders

text:
# Question
Title: ResourceContentManager with folders
I am attempting to do something like the following: Link (Access the content via a DLL)

However, I need to maintain the folder structure of the fonts and images. I have attempted to add the folders to the resources file, but it doesn't add the folder if I drop it in the resources file in VS. I am thinking I might need to embed the content as just a regular folder, and each file will need its property to be set to embedded resource, but I need to use it in another assembly.

I looked at: http://zacharysnow.net/2010/07/03/xna-load-texture2d-from-embedded-resource/ but I think I can only do that with textures. I need to do it with fonts as well.

I looked at: https://stackoverflow.com/questions/859699/how-to-add-resources-in-separate-folders and that doesn't seem to help me much.

Whats the best way I can embed my resources in another assembly, while maintaining my content loading strings?

# Answer
Right click the `.resx` file and select "View Code". You'll find a tag like the following:

```
<data name="Blah" type="System.Resources.ResXFileRef, System.Windows.Forms">
  <value>Resources\Blah.xnb;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>

```

The name that `ResourceContentManager` searches for is the `name` attribute in the `Data` tag. The location that the file comes from (in the `value` tag) doesn't matter. While it does cause the compiler to emit a warning, the easiest way to get the resource to be loaded by the name you want you want is to rename it to "`Folder\Blah`" or similar (note the *back* slash). There is no concept of folders here - it's just a name.

---

I am having a *lot* of difficulty verifying this - but "Embedded Resource" (the build option) seems to be *different* to embedding using a `resx` file. `ResourceContentManager` does not support loading files embedded this way.

*However*, it is pretty simple to create a class like `ResourceContentManager` to load "Embedded Resource" resources. Here's some tested, working code to do exactly that:

```
class EmbeddedResourceContentManager : ContentManager
{
    public EmbeddedResourceContentManager(IServiceProvider serviceProvider)
        : base(serviceProvider) { }

    protected override Stream OpenStream(string assetName)
    {
        assetName = "YourNamespace." + assetName.Replace('\\', '.') + ".xnb";
        return Assembly.GetExecutingAssembly().GetManifestResourceStream(assetName);
    }
}

```

Note the way it converts the supplied path into the path expected by `GetManifestResourceStream`. If you have trouble with getting the path to work - check what the actual paths are with `GetManifestResourceNames`.

Doing it this way will save you having to create and manage a `.resx` file. And it will allow you to use the folder structure as exposed in Visual Studio.
> 1 votes

---
Tags: xna, c#, xna-content-pipeline
---


# Question
Title: Is it worth taking the time and making a game scripting engine instead of directly coding?
I don't know exactly everything there is to game programming and I forget things so I like to write libraries that are easy to use so I can use the thing that's hard to do such as file serialization. Anyway this brought me to a question, should I write a small game engine that writes code such as rendering objects for me and all I have to do it use a GUI? I know it takes a long time to do but the question is whether it's worth it and will it save time to do it.

# Answer
Any graphical programming language is really geared towards people who are not programmers. It all deals with abstractions at some level. You'll eventually find some edge case you didn't prepare for, then have to implement that case in your system before you use it.

If you're good enough at programming to write a system that actually works well, then you're a good enough programmer to actually write the code itself or (more likely) more comfortable with just writing the code directly.

If not, then you're likely not going to be able to author a system like you want.

Short answer: no.

That being said, there are engines and tools that abstract out a lot of that stuff for you. Specifically, look at using the Unity engine with the Playmaker addon: http://www.hutonggames.com/showcase.html
> 2 votes

# Answer
No. What scripting are you even going to support? Write Games, Not Engines. It sounds like you're just trying to make tech for tech's sake, not solve an actual problem. Make a real game and see what comes of that. If you end up with s useful generic game tool, fine. Set out to make an actual, specific game, though.
> 2 votes

# Answer
One reason you would want to write a game scripting engine is if you wanted your engine to run on multiple platforms. You could then separate programming concerns into the low-level platform details and the high-level game.

Imagine you've written a game that supports PC, iOS and Android. Now you want to put out a major update to the game. Having all 3 platforms share a common scripting language could be the difference between copy/paste and serious programming effort.
> 0 votes

# Answer
It can't possibly save time on a single project because whatever you need for the game will need to be in the engine, plus anything the game doesn't need but the engine does.

Generally speaking you should write games, not engines. Writing engines takes longer, and the engine won't be good enough unless you have enough experience to make it correctly, and you won't know what needs to go into it until you have made a full game with it. For that reason, new engines should usually be created based on finished games, not the other way around.
> 0 votes

---
Tags: gui
---


title: Best approach for Event driven UI

text:
# Question
Title: Best approach for Event driven UI
Had an idea for a modification to a game, however the core functionality heavily involves UI, and the API for the mod is event based.

The player will have there own custom data object, so I know one option could be

```
onClickEvent {
if Player doing X task { player.doX}
if Player doing Y task { player.doY }
}

on ScrollEvent {
if Player doing X task { player.setXValue}
}

```

I have a feeling this is not the best approach, so my question is what is the best approach to an event driven UI?

# Answer
> 1 votes
There are many ways to handle events. Direct dispatch is the easiest, but least efficient in many cases. When an event happens, generate the event object and then pass it off to the HandleEvent method of any potentially interested game object. Since the GO does its own event filtering, this gets expensive as the number of events and interested GO list grows.

You can remove the manual filtering by giving each event object a virtual SendTo method that selects the correct handler. The InputEvent might call OnInput on the target GO, while the CollisionEvent might call OnCollision. The handlers can be empty virtual functions in the base GO class.

To get around the expense, consider using an observer pattern for some events. The GO registers which events it cares about and which handler to call. Then events are only delivered to the objects that are *actually* interested, not just potentially interested. You can keep the list of registrations in a Dictionary on the event emitter object (eg your InputSystem) easily.

It's common to have a mix of event delivery methods. Some events make more sense in an observer system, some in a direct dispatch system.

# Answer
> 1 votes
It's very similar to non event driven and is a bit harder. This is what it would look like:

```
if (Mouse.isLeftButtonClicked && Mouse.isOverControl(Controls.addButton))
    Event.fire(events.addButtonEvent);
//ect

```

And:

```
void AddButtonClickedEvent()
{
    MessageBox("You Clicked The Add Button!");
}
//ect

```

So it's pretty much the same on the inside, and it uses more resources. Events are used by things such as Visual C# so it's easier for the programmer since you not making the events most of the time. It would have just been easier to do:

```
if (Mouse.isLeftButtonClicked && Mouse.isOverControl(Controls.addButton))
    MessageBox("You Clicked The Add Button!");

```

Some of the code is messier but it's still better.

Although if I were to go with events I would do something like my example of events above.

---
Tags: gui, events
---


title: Why use textures that are Power of Two?

text:
# Question
Title: Why use textures that are Power of Two?
> **Possible Duplicate:**
> Why are textures always square powers of two? What if they aren’t?

I am using C# and XNA (also MonoGame for other platforms than Windows) to create a game in 2D. Ususally for all textures I use the NVidia plugin for Photoshop to create DDS files with precomputed mip-maps (either full color, or DXT-5).

How important is it, nowadays, to stick to textures with extensions that are a power of two? What are the advantages and disadvantages of doing so?

The background of my question for that I use a number of quite large background images in with 1980 x 1080 pixels in size and storing them in textures of 2048 x 2048 pixels size seems like a tremendous waste of memory.

Let me stress that I am aware that having only power-of-two textures has been important in the past for certain specific optimizations BUT I would like to know whether this TODAY (GPUs of the last ~2 years, current consoles etc.) is still required?

# Answer
> 8 votes
There are probably 2 main reasons:

1. **Creating MipMaps** \- when you want to create an image with 2x smaller resolution, you just divide the width and the height by two and compute the average of 2x2 pixels of a big image into 1 pixel of a small image. Thanks to PowerOfTwo, the process can be repeated until some dimension reaches 1. E.g. sizes 512x128, 256x64, 128x32, 64x16, 32x8, 16x4, 8x2, 4x1. Try to do that without POT at the beginning.
2. **Repeating textures** \- let's say your texture is 200px wide and you want to get the pixel at x=311. To get your pixel, you should access the (311%200)=111th pixel of bitmap. But if the width was POT, e.g. 256, you can access (311&255)=56th pixel. Computing "%" is about 100x slower than "&" (because of division). So with POT, accessing textures is 100x faster.

These reasons are purely mathematical and no hardware or software improvement can change that.

# Answer
> 2 votes
Are we talking mobile GPUs or desktop?

Desktop GPUs (that is the `HiDef` profile in XNA) will handle non-power-of-two textures just fine - with maybe a bit of performance degradation in some cases (same as those listed below). See Ivan Kuckir's answer for additional details.

Some older and Mobile GPUs (or the software for them; `Reach` profile in XNA) emulate non-power-of-two support by bumping the internal texture size up to the next power-of-two. This extra border of "undefined" data around the texture means that **mipmaps**, **wrapping** and **DXT compression** are impossible (instead of simply being slow). It also wastes memory for you.

In your case, using a non-power-of-two texture is not a problem, providing you do not use those three features on the `Reach` profile. For such large backgrounds, the inability to use DXT compression is painful. But if you're targeting `HiDef`, by all means use it, even with non-power-of-two textures - it's almost certainly worth it.

# Answer
> 1 votes
In the end you're dealing with fitting little blocks of memory into a big block of memory, some underlying hardware constraints, time/space sensitive compression to match, and a requirement for maximal usage with minimal fragmentation over a random duty cycle.

Solution = pow2 sizes to make blocks fit together more easily, to align with a variety of underlying hardware, and to allow for optimized block compression that may or may not reside in hardware.

---
Tags: xna, c#, 2d, graphics, textures
---


# Question
Title: How can I get a pointer to ID3DX11EffectShaderVariable from ID3DX11Effect
I'm using the DirectX Effects framework and I want to create an input layout automatically when compiling an effect. I've tried to call ID3DX11Effect-\>GetVariableByName() with the shader's name, to obtain a pointer to a ID3DX11EffectVariable interface, then doing ID3DX11EffectVariable-\>AsShader() to obtain a pointer to a ID3DX11EffectShaderVariable interface. The problem is that the pointer returned by ID3DX11Effect-\>GetVariableByName() is not valid (the IsValid() method returns false). So how can I get a pointer to the shaders of an effect file ?

# Answer
The effect framework is based around the concepts of techniques and passes, so you will need to go through these to get to your shader. The API will let you get a list of techniques in the effect and a list of passes in a technique; you can then extract the shaders from the pass.

Here is the code from my engine that extracts the vertex shader from the first pass of the first technique of an effect and goes through its input signature. I've removed the error checking for brevity, but you can see how it would work.

```
ID3DX11EffectTechnique * pTech = m_pEffect->GetTechniqueByIndex(0);
D3DX11_TECHNIQUE_DESC techDesc;
pTech->GetDesc(&techDesc);

ID3DX11EffectPass * pPass = pTech->GetPassByIndex(0);
D3DX11_PASS_DESC passDesc;
pPass->GetDesc(&passDesc);

D3DX11_PASS_SHADER_DESC vsPassDesc;
pPass->GetVertexShaderDesc(&vsPassDesc);

ID3DX11EffectShaderVariable * pVs;
pVs = vsPassDesc.pShaderVariable->AsShader();

D3DX11_EFFECT_SHADER_DESC vsDesc;
pVs->GetShaderDesc(0, &vsDesc);

// Build the vertex format
for (UINT iInput = 0; iInput < vsDesc.NumInputSignatureEntries; ++iInput)
{
    D3D11_SIGNATURE_PARAMETER_DESC inputDesc;
    pVs->GetInputSignatureElementDesc(0, iInput, &inputDesc);
    // do something with the input element...
}

```
> 1 votes

---
Tags: directx, shaders
---


# Question
Title: Moon lander, gravity + velocity for an image
Hey its my first year doing java so I'm still quite bad.

I'm making a lunar lander for my coursework and I'm struggling to make some kind of gravity to pull my rocket with increasing speed, and I cant find a way of my rocket to move with increasing speed in any direction. Here is my code

import javax.swing.JFrame;

import java.awt.Color;

import java.util.Random;
import javax.swing.Timer;

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

import java.awt.image.BufferedImage;

public class LunarLander extends JFrame {

```
private static JFrame window;

private static Graphics gr;

private static Image theBackground;
private static Image theLander;
private static Image theBang;
private static Image theBottomFlame;
private static Image theLeftFlame;
private static Image theRightFlame;
private static Image theFlag;
private static Image theLandingSite;

private static int landerX=350, landerY=20;
private static boolean explosion=false;
private static int fuel=740;

private static int landingY;
private static boolean stop_moving=false;

private static boolean fuel_stoped =  false;

public static void main(String[] args) {
    window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLocation(550,10);
    window.setTitle("Houston, we have a Problem");
    window.setSize(1024,768);
    window.setResizable(false);

    BufferedImage canvas=new BufferedImage(1024,768,BufferedImage.TYPE_INT_ARGB);
    gr=canvas.getGraphics();
    JLabel label=new JLabel(new ImageIcon(canvas));
    window.add(label);

    window.setVisible(true);
    theBackground = GameImage.loadImage("Images//Background.jpg");
    theLander = GameImage.loadImage("Images//Rocket.png");
    theBang   = GameImage.loadImage("Images//explosion.gif");
    theBottomFlame  = GameImage.loadImage("Images//flamebottom.png");
    theLeftFlame  = GameImage.loadImage("Images//flameleft.png");
    theRightFlame  = GameImage.loadImage("Images//flameright.png");
    theFlag  = GameImage.loadImage("Images//flag.png");
    theLandingSite  = GameImage.loadImage("Images//site.png");

    GameKeyboard.initialise();

    ActionListener taskPerformer = new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {
                doTimerAction();
            }
        };
    Timer t = new Timer(25, taskPerformer);
    t.start();

   }

static Random randomGenerator = new Random();
static int landingX = randomGenerator.nextInt(900);

private static boolean check_position(int x, int y){
    String CHECK="";
    if(y>485 && y<600){
        if(x>landingX-150 && x<landingX+20) {
            CHECK="TRUE";
            stop_moving = true;
        }
    }else{
        CHECK="FALSE";
    }
    if(CHECK=="TRUE"){
        return true;
    }else{
        return false;
    }
}

private static void doTimerAction() {

    gr.drawImage(theBackground, 0, 0, null);
    gr.drawImage(theLandingSite, landingX , landingY+670, null);
    char key= GameKeyboard.getKey();
    int  specialKey=GameKeyboard.getSpecialKey();

    gr.setColor( Color.orange );
    gr.setFont(new Font("Arial", Font.PLAIN, 16));
    gr.drawString("LEFT RIGHT UP and DOWN arrow keys to move", 10,80);
    gr.drawString("Key="+key+" specialKey="+specialKey ,10,100);
    if (stop_moving == false){
        if(fuel_stoped==false){
            if (explosion == false) {

                switch (key) {

                    case 'W': landerY=landerY-3; --fuel; gr.drawImage(theBottomFlame, landerX+148, landerY+195, null); break;
                    case 'w': landerY=landerY-3; --fuel; gr.drawImage(theBottomFlame, landerX+148, landerY+195, null); break;
                    case 'S': landerY=landerY+1;  break;
                    case 's': landerY=landerY+1;  break;
                    case 'A': landerX=landerX-1; --fuel; gr.drawImage(theRightFlame, landerX+189, landerY+83, null); break;
                    case 'a': landerX=landerX-1; --fuel; gr.drawImage(theRightFlame, landerX+189, landerY+83, null); break;
                    case 'D': landerX=landerX+1; --fuel; gr.drawImage(theLeftFlame, landerX+115, landerY+83, null); break;
                    case 'd': landerX=landerX+1; --fuel; gr.drawImage(theLeftFlame, landerX+115, landerY+83, null); break;
                    case 'Q': landerY=landerY-3;  landerX=landerX-2; gr.drawImage(theRightFlame, landerX+189, landerY+83, null);gr.drawImage(theBottomFlame, landerX+148, landerY+195, null); --fuel;break;
                    case 'q': landerY=landerY-3;  landerX=landerX-2; gr.drawImage(theRightFlame, landerX+189, landerY+83, null);gr.drawImage(theBottomFlame, landerX+148, landerY+195, null); --fuel; break;
                    case 'E': landerY=landerY-3;  landerX=landerX+2; gr.drawImage(theLeftFlame, landerX+115, landerY+83, null); gr.drawImage(theBottomFlame, landerX+148, landerY+195, null);  --fuel; break;
                    case 'e': landerY=landerY-3;  landerX=landerX+2; gr.drawImage(theLeftFlame, landerX+115, landerY+83, null); gr.drawImage(theBottomFlame, landerX+148, landerY+195, null);  --fuel; break;

                }

            }
        }

             }

    // If the lander hasn't hit the ground yet, draw it and the rocket flame
    if(landerY < 550) {

        gr.drawImage(theLander, landerX, landerY, null);

    }
    // If it is at the bottom draw and explosion again for a while, i.e. <400
    else if (landerY < 600) {
        gr.drawImage(theBang, landerX, landerY, null);
        gr.setFont(new Font("Arial", Font.BOLD, 40));
        gr.setColor( new Color(255, 100,100) );
        gr.drawString("GAME OVER", 400,400);
        explosion = true;
        //landerY = 560;

    }

    if(check_position(landerX, landerY)) {
        gr.setFont(new Font("Arial", Font.BOLD, 40));
        gr.setColor( new Color(255, 100,100) );
        gr.drawString("Well Done", 400,400);
        gr.drawImage(theFlag, landingX+180 , landingY+540, null);
        stop_moving = true;

    }

   if(fuel<5){
    fuel_stoped= true;
       }

    // Example how to do non-image graphics, i.e. graphics that is created at runtime.
    // Here a fuel gauge ('fuel' is decreased by one every time this method is run.
    if(landerY < 550) {

        gr.setColor( new Color(200, 200, 200) ); //grey background
        gr.fillRect(1000, 0, 23, 800);

        if(fuel>200)        gr.setColor( new Color(0, 255, 0) );    // green
        else if(fuel>100)   gr.setColor( new Color(255, 255, 0) );  // yellow
        else                gr.setColor( new Color(255, 0, 0) );    // red
        gr.fillRect(1003, 755-fuel, 16, fuel);
    }

    window.repaint();

}

```

# Answer
> 5 votes
Well i haven't gone through the whole code but did notice one thing that you don't have any track of velocity.

well a simple tip to mimic gravity would be use a vector for position of object, velocity and gravity.

```
position.x=350; position.y=20;
velocity.x=0; velocity.y=0;
gravity.x=0; gravity.y=1; //depending on the strength of the gravity

//Update the position of object by adding velocity to it
position+=velocity;

//in case of keystrokes manipulate velocity rather that the position itself
case "w":velocity.y-=1;   //similarly for other cases

//constantly keep adding gravity to velocity
velocity+=gravity;

```

Hope you got the idea

---
Tags: java
---


# Question
Title: How bad would be to focus on iOS/Android development for an indie developer?
After some time developing games for others I'm thinking of moving towards my own productions. My background is 10+ years of software development, with last 2 years spent on the iOS development (Objective-C and CoronaSDK).

With my current experience in Corona I can quickly develop for iOS and Android systems. And this is something that I'm probably gonna do with several of the game ideas I have, at least for the prototype part.

But - I'm wondering if it's not a bad idea to focus on those 2 systems only. After all there are other mobile platforms, there are PCs, Macs and Linux boxes... All of them having gamers using them.

I was wondering if it wasn't a good idea to try some other SDK, giving me more flexibility when it comes to platform-independance. There's Unity3D (I think I can develop a 2D game in it though), there's MoAI from what I checked.

I see a few options, not sure which one is best as I have little experience in this field (publishing own games):

1. Stick with CoronaSDK for the whole time, release for iOS and Android platforms, screw other mobile devices and PCs,
2. Use Corona for prototyping, then when the idea goes more into the "production" phase rewrite it in MoAI or Unity3D for more platforms support,
3. Start with one of those 2 SDKs right now (which means the prototype phase will be delayed a bit, but after that I can jump right into real coding).

Any clues here, what to do?

# Answer
> But - I'm wondering if it's not a bad idea to focus on those 2 systems only. After all there are other mobile platforms, there are PCs, Macs and Linux boxes... All of them having gamers using them.

If you want to make money on your games, and even if you don't, you just want to reach a large audience, there really are no other mobile platforms. Android, iphone make up most of the market, with RIM dying out, and Windows Phone barely making a dent.

If you think you have the time, then there's no harm in experimenting with other SDKs. Just learning how to efficiently use new tech can take some time though. I would go with option 1 if you're just trying to get a game out.
> 6 votes

# Answer
If you already have access to Corona SDK I think you should stick to it for a while. You can build up presence on those two platforms and later you can move onto others with solid game portfolio which you can reference later on. Also instead of wasting time learning a new environment you can experiment with game ideas and business models with an SDK you already know.

It sounds good that you can start learning Unity without buying it but as time passes you are going to miss the pro version features and the ability to build onto mobile platforms and that costs a fortune. (With Corona SDK and Unity in mind you might prefer fancy tools for game creation but if you are interested in other possibilities libGDX is a free alternative)
> 2 votes

# Answer
just wanted to chime in and say this is kind of what i'm planning on doing also! I am currently using Corona SDK and am building my prototype right now. Planning on starting my own one man indie game dev studio (wfh) and with Corona, iOS and Android will be my only target markets.

My plan is currently to subscribe to corona for one year and see through that year. If all goes well - right now, i find corona easy and quick, and lua also - i may switch over to moai. I would like to stick with lua.

With the type of games i am thinking of building, and with the strength of smartphone and tablet devices, i think just targeting iOS and Android will be enough for the time being.
> 0 votes

# Answer
iOS and Android combined are large markets, with OUYA and NVIDIA Shield around the corner, Android is definitely going to be a hot spot to consider since minimal changes can be made to support these platforms. However, don't limit yourself because you like a specific platform, put that game on anything with a screen and an input device.

SDKs aside, if you want to maximize your audience then you should consider getting your game on Kongregate, Desura and if you've got something great, Steam Greenlight. You've also got console opportunities with PlayStation Mobile although I don't know how large that audience is.
> 0 votes

---
Tags: android, ios, cross-platform
---


title: Images not rendering in Slick

text:
# Question
Title: Images not rendering in Slick
I have built a game that uses the Slick framework. The maps are tmx files and were built using TileD. The game iterates through a list of players and maps - once a game with a player and map is completed the next game launches with a new player and map. Right now, the first time the game runs the tiles and map are displayed correctly. If I reuse the same tile files in a map (or reuse the same map) those tile files do not render - we just get a bunch of white tiles where our tiles should have loaded as seen here: white blocks. This is what it should look like: correct rendering. Note the game still works 100% correctly - the tiles just don't load. We also don't see any rendering issues if we rename the tile image files and use those in a map. Does anyone have any insight on why reusing maps/tiles would cause them not to load?

Here are portions of the code. Render code:

````
 public void render(GameContainer container, Graphics g)  {
        map.getMap().render(320 - (int) ((float)player.getPlayerGridLocation().getX()*16),
                240 - (int) ((float)player.getPlayerGridLocation().getY()*16));
        g.drawAnimation(player.getPlayerAnimation(), (640/2),(480/2));
    }
````

Launching the games:

```
for (int playerIndex = 0; playerIndex < players.length; playerIndex++) {
    for (int mapIndex = 0; mapIndex < maps.length; mapIndex++) {
        startMaze(maps[mapIndex], players[playerIndex]);
    }
}

```

Code in the startMaze function that launches a game:

```
DungeonMaze dm = new DungeonMaze();
container = new AppGameContainer(dm, 640, 480, false);
container.start();

```

Code that ends a game:

```
container.setForceExit(false);
container.exit();

```

Map code:

public class Map {
    private Point MapSize;
    private int MapBoxWidth;
    static MapBox[][] MapGrid;
    BoxType[][] Grid;
    private TiledMap map;
    private String name = "";

```
public void setMap(String mapName) throws SlickException {
    map = null;
    try {
         map = new TiledMap("res/" + mapName, true);
         name = mapName;
         initMap();
     } catch (Exception e) {
         e.printStackTrace();
     }
}

public String getMapName() {
    return name;
}

private void initMap() {
     MapSize = new Point(map.getWidth(),map.getHeight());
    //System.out.print(MapSize.getX());
    //System.out.print(MapSize.getY());

    MapBoxWidth = map.getTileHeight();
    MapGrid = new MapBox[(int) MapSize.getX()][(int) MapSize.getY()];
    Grid = new BoxType[(int) MapSize.getX()][(int) MapSize.getY()];

    // Get the index #s of each layer of the TMX map file.
    // * we could probably write this as a loop to get every layer in the map
    int collisionIndex = map.getLayerIndex("collision");
    int keyIndex = map.getLayerIndex("key");
    int doorIndex = map.getLayerIndex("door");
    int endIndex = map.getLayerIndex("end");

    for(int i = 0; i < (int)MapSize.getX(); i++) {
        for(int j = 0; j < (int)MapSize.getY(); j++) {
            BoxType curType = BoxType.Open;

            int tileID = map.getTileId(i,j,collisionIndex);
            String property = map.getTileProperty(tileID, "collide", "false");
            if(property.equals("true")) {
                curType = BoxType.Blocked;
            }

            tileID = map.getTileId(i,j,keyIndex);
            property = map.getTileProperty(tileID, "keyed", "false");
            if(property.equals("true")) {
                curType = BoxType.Key;
                /*System.out.print(i);
                System.out.print("-");
                System.out.print(j);
                System.out.print("Key\n");*/
            }

            tileID = map.getTileId(i,j,doorIndex);
            property = map.getTileProperty(tileID, "doored", "false");
            if(property.equals("true")) {
                curType = BoxType.Door;
                /*System.out.print(i);
                System.out.print("-");
                System.out.print(j);
                System.out.print("Door\n"); */
            }

            tileID = map.getTileId(i,j,endIndex);
            property = map.getTileProperty(tileID, "ended", "false");
            if(property.equals("true")) {
                curType = BoxType.Exit;
                /*System.out.print(i);
                System.out.print("-");
                System.out.print(j);
                System.out.print("Exit\n");*/
            }

            Grid[i][j] = curType;
        }
    }

    for(int i = 0; i < (int)MapSize.getX(); i++) {
        for(int j = 0; j < (int)MapSize.getY(); j++) {
            BoxType North = BoxType.Open;
            BoxType South = BoxType.Open;
            BoxType East = BoxType.Open;
            BoxType West = BoxType.Open;

            if(i == 0) {West = BoxType.Blocked;}
            else {West = Grid[i-1][j];}

            if(i == (int)MapSize.getX() - 1) {East = BoxType.Blocked;}
            else {East = Grid[i+1][j]; }

            if(j == 0) {North = BoxType.Blocked;}
            else {North = Grid[i][j-1];}

            if(j == (int)MapSize.getY() - 1) {South = BoxType.Blocked;}
            else {South = Grid[i][j+1];}

            boolean consumable = false;
            if (Grid[i][j] == BoxType.Key){ consumable = true;}

            boolean end = false;
            if (Grid[i][j] == BoxType.Exit){ end = true;}

            MapGrid[i][j] = new MapBox(North, South, East, West, consumable, end);
        }
    }
}

// Constructor for Map, load map from resources folder
public Map() throws SlickException {
    //map = new TiledMap("res/map02.tmx");
}

// Return the entire TMX map as a TiledMap
public TiledMap getMap() {
    return map;
}

// Return the contents of a specific MapBox space
public MapBox getMapBox(Point box) {
    return MapGrid[(int) box.getX()][(int) box.getY()];
}

// Returns the size of the overall map as X,Y coordinate
public Point getMapSize() {
    return MapSize;
}

public void pickup(Point playerLocation) { //thought key was still exsiting to south
    //MapBox Location = MapGrid[(int) playerLocation.getX()][(int) playerLocation.getY()];
    MapGrid[(int) playerLocation.getX()][(int) playerLocation.getY()].consume();

    if(playerLocation.getX() > 0) {
        MapBox WestBox = MapGrid[(int) playerLocation.getX()-1][(int) playerLocation.getY()];
        MapGrid[(int) playerLocation.getX()-1][(int) playerLocation.getY()] = new MapBox(WestBox.North, WestBox.South, BoxType.Open, WestBox.West, WestBox.hasKey(), WestBox.isEnd());
    }
    if(playerLocation.getX() < MapSize.x) {
        MapBox EastBox = MapGrid[(int) playerLocation.getX()+1][(int) playerLocation.getY()];
        MapGrid[(int) playerLocation.getX()+1][(int) playerLocation.getY()] = new MapBox(EastBox.North, EastBox.South, EastBox.East, BoxType.Open, EastBox.hasKey(), EastBox.isEnd());
    }
    if(playerLocation.getY() > 0) {
        MapBox SouthBox = MapGrid[(int) playerLocation.getX()][(int) playerLocation.getY()+1];
        MapGrid[(int) playerLocation.getX()][(int) playerLocation.getY()-1] = new MapBox(BoxType.Open, SouthBox.South, SouthBox.East, SouthBox.West, SouthBox.hasKey(), SouthBox.isEnd());
    }
    if(playerLocation.getY() < MapSize.y) {
        MapBox NorthBox = MapGrid[(int) playerLocation.getX()][(int) playerLocation.getY()-1];
        MapGrid[(int) playerLocation.getX()][(int) playerLocation.getY()+1] = new MapBox(NorthBox.North, BoxType.Open, NorthBox.East, NorthBox.West, NorthBox.hasKey(), NorthBox.isEnd());
    }

    int tilesIndex = map.getLayerIndex("tiles");

    int keyIndex = map.getLayerIndex("key");
    int tileID = map.getTileId((int) playerLocation.getX(),(int) playerLocation.getY(),tilesIndex);
    map.setTileId((int) playerLocation.getX(), (int) playerLocation.getY(), keyIndex, tileID);
}

public boolean unlockDoor(Point playerLocation) {
    MapBox Location = MapGrid[(int) playerLocation.getX()][(int) playerLocation.getY()];
    Point DoorLocation = new Point();

    //check for each direction for a door
    if(Location.North == BoxType.Door) {
        DoorLocation.x = (int) playerLocation.getX();
        DoorLocation.y = (int) playerLocation.getY()-1;
    }
    else if(Location.South == BoxType.Door) {
        DoorLocation.x = (int) playerLocation.getX();
        DoorLocation.y = (int) playerLocation.getY()+1;
    }
    else if(Location.East == BoxType.Door) {
        DoorLocation.x = (int) playerLocation.getX()+1;
        DoorLocation.y = (int) playerLocation.getY();
    }
    else if (Location.West == BoxType.Door) {
        DoorLocation.x = (int) playerLocation.getX()-1;
        DoorLocation.y = (int) playerLocation.getY();
    }
    else { //no door, return false
        //System.out.print("unlock failed\n");
        return false;
    }

    //MapBox Door = MapGrid[DoorLocation.x][DoorLocation.y];

    //MapGrid[(int) playerLocation.getX()][(int) playerLocation.getY()].consume();

    if(DoorLocation.getX() > 0) {
        MapBox WestBox = MapGrid[(int) DoorLocation.getX()-1][(int) DoorLocation.getY()];
        MapGrid[(int) DoorLocation.getX()-1][(int) DoorLocation.getY()] = new MapBox(WestBox.North, WestBox.South, BoxType.Open, WestBox.West, WestBox.hasKey(), WestBox.isEnd());
    }
    if(DoorLocation.getX() < MapSize.x) {
        MapBox EastBox = MapGrid[(int) DoorLocation.getX()+1][(int) DoorLocation.getY()];
        MapGrid[(int) DoorLocation.getX()+1][(int) DoorLocation.getY()] = new MapBox(EastBox.North, EastBox.South, EastBox.East, BoxType.Open, EastBox.hasKey(), EastBox.isEnd());
    }
    if(DoorLocation.getY() < MapSize.y) {
        MapBox SouthBox = MapGrid[(int) DoorLocation.getX()][(int) DoorLocation.getY()+1];
        MapGrid[(int) DoorLocation.getX()][(int) DoorLocation.getY()+1] = new MapBox(BoxType.Open, SouthBox.South, SouthBox.East, SouthBox.West, SouthBox.hasKey(), SouthBox.isEnd());
    }
    if(DoorLocation.getY() > 0) {
        MapBox NorthBox = MapGrid[(int) DoorLocation.getX()][(int) DoorLocation.getY()-1];
        MapGrid[(int) DoorLocation.getX()][(int) DoorLocation.getY()-1] = new MapBox(NorthBox.North, BoxType.Open, NorthBox.East, NorthBox.West, NorthBox.hasKey(), NorthBox.isEnd());
    }

    //System.out.print("unlocked\n");

    int tilesIndex = map.getLayerIndex("tiles");

    int doorIndex = map.getLayerIndex("door");
    int tileID = map.getTileId((int) DoorLocation.getX(),(int) DoorLocation.getY(),tilesIndex);
    map.setTileId((int) DoorLocation.getX(), (int) DoorLocation.getY(), doorIndex, tileID);
    return true;
}

// Return the size of the MapBox
public int getMapBoxWidth() {
    return MapBoxWidth;
}

```

}

# Answer
> 1 votes
Ok so lets get to it!

Paste the code where you call your first map to initialise. Do you use the setMap() method to initialise your first map? or do you have map = new TiledMap("blah");??

If you can't figure out the problem with my example code then you might have to paste your code on pastebin and let me thoroughly read and test it.

Here is my example of loading a TiledMap and changing maps at runtime using key's 1 & 2. Here is also a link to my youtube channel where i have posted a short video for you to see this in action :) TiledMap: Change at runtime test

```
package test;

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

public class Game extends BasicGame {

public TiledMap map;

public Game() {
    super("TileMap Test");
}

public void setMap(String mapName) throws SlickException {
    map = null;
    map = new TiledMap("res/" + mapName + ".tmx");
}

@Override
public void init(GameContainer gc) throws SlickException {
    setMap("tilemaptest");
}

@Override
public void update(GameContainer gc, int delta) throws SlickException {
    Input input = gc.getInput();

    if (input.isKeyPressed(Input.KEY_1)) {
        setMap("tilemaptest");
    }

    if (input.isKeyPressed(Input.KEY_2)) {
        setMap("tilemaptest2");
    }
}

@Override
public void render(GameContainer gc, Graphics g) throws SlickException {
    map.render(0, 0);
}

public static void main(String[] args) throws SlickException {
    AppGameContainer app = new AppGameContainer(new Game());
    app.setDisplayMode(640, 480, false);
    app.setTargetFrameRate(60);
    app.start();
}

}

```

Let me know how you go :)

# Answer
> 0 votes
Ended up figuring out what the issue was after running Savlon's example above. The issue was with how I was restarting the game. I was starting and stopping the AppGameContainer i n a separate file which was causing some sort of issue with the rendering in subsequent runs. After rewriting the code, I changed it so that in the update function of my BasicGame class when a game completes the GameContainer reinitializes (reinit()). That ended up solving the weird rendering issue.

Thanks for your help Savlon - you example ended up pointing me in the right direction!

---
Tags: rendering, tiles, slick, image
---


# Question
Title: How can I load 2D texture data without a GraphicsDevice instance?
We have a client/server architecture for our game with the client being the XNA Game, and the game server is separate and only references XNA. They both use a shared DLL for networking. The game server is windows forms for just starting/restarting and some stats output, and does no drawing or anything.

The problem is I need to load Texture2D's on the game server, to get width/height information, and for the server to be able to do per pixel collision detection for its simulation. However, it seems a Texture2D requires a GraphicsDevice to instantiate. And it appears a GraphicsDevice requires an XNA Game?

Is there some way I can load a Texture2D into memory on the server without a graphics device, or some way to instantiate a GraphicsDevice to do this (even though nothing is going to be drawn)?

# Answer
Texture2D is a very specific class that is used to load an image into something the GPU can easily consume and use as-is. You wouldn't want all this kind of data and the like inside of a server program. I'm going to give some advice here on what I think you want, feel free to comment if I don't meet your requirements.

First of all: **I don't think you need per pixel collision checking on the server.**

I don't know your game requirements or what kind of game you're trying to make but you should know that if you're hosting any more than a few moving clients at once that per-pixel collision for every movement for a LOT of clients is going to be expensive, and this probably is not what you want. You should look into a way of optimizing this. With this in mind, you may decide this is not the best route after all or decide this is necessary. Give this some thought, we'll return to it soon.

**Next, are the height and width still necessary?**

If your answer is **yes, continue on.**

The answer is to not read the entire file on the server and just extract what you need. The obvious thing may be to use a Bitmap object of some sort and just load like that - but the faster and more elegant approach is to just read the file headers and grab the information yourself. This StackOverflow post outlines a few method(s). For reference, I've included my favorite here:

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

namespace ImageDimensions
{
    public static class ImageHelper
    {
        const string errorMessage = "Could not recognise image format.";

        private static Dictionary<byte[], Func<BinaryReader, Size>> imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>()
        {
            { new byte[]{ 0x42, 0x4D }, DecodeBitmap},
            { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },
            { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },
            { new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },
            { new byte[]{ 0xff, 0xd8 }, DecodeJfif },
        };

        /// <summary>
        /// Gets the dimensions of an image.
        /// </summary>
        /// <param name="path">The path of the image to get the dimensions of.</param>
        /// <returns>The dimensions of the specified image.</returns>
        /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
        public static Size GetDimensions(string path)
        {
            using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)))
            {
                try
                {
                    return GetDimensions(binaryReader);
                }
                catch (ArgumentException e)
                {
                    if (e.Message.StartsWith(errorMessage))
                    {
                        throw new ArgumentException(errorMessage, "path", e);
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// Gets the dimensions of an image.
        /// </summary>
        /// <param name="path">The path of the image to get the dimensions of.</param>
        /// <returns>The dimensions of the specified image.</returns>
        /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
        public static Size GetDimensions(BinaryReader binaryReader)
        {
            int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length;

            byte[] magicBytes = new byte[maxMagicBytesLength];

            for (int i = 0; i < maxMagicBytesLength; i += 1)
            {
                magicBytes[i] = binaryReader.ReadByte();

                foreach(var kvPair in imageFormatDecoders)
                {
                    if (magicBytes.StartsWith(kvPair.Key))
                    {
                        return kvPair.Value(binaryReader);
                    }
                }
            }

            throw new ArgumentException(errorMessage, "binaryReader");
        }

        private static bool StartsWith(this byte[] thisBytes, byte[] thatBytes)
        {
            for(int i = 0; i < thatBytes.Length; i+= 1)
            {
                if (thisBytes[i] != thatBytes[i])
                {
                    return false;
                }
            }
            return true;
        }

        private static short ReadLittleEndianInt16(this BinaryReader binaryReader)
        {
            byte[] bytes = new byte[sizeof(short)];
            for (int i = 0; i < sizeof(short); i += 1)
            {
                bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();
            }
            return BitConverter.ToInt16(bytes, 0);
        }

        private static int ReadLittleEndianInt32(this BinaryReader binaryReader)
        {
            byte[] bytes = new byte[sizeof(int)];
            for (int i = 0; i < sizeof(int); i += 1)
            {
                bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();
            }
            return BitConverter.ToInt32(bytes, 0);
        }

        private static Size DecodeBitmap(BinaryReader binaryReader)
        {
            binaryReader.ReadBytes(16);
            int width = binaryReader.ReadInt32();
            int height = binaryReader.ReadInt32();
            return new Size(width, height);
        }

        private static Size DecodeGif(BinaryReader binaryReader)
        {
            int width = binaryReader.ReadInt16();
            int height = binaryReader.ReadInt16();
            return new Size(width, height);
        }

        private static Size DecodePng(BinaryReader binaryReader)
        {
            binaryReader.ReadBytes(8);
            int width = binaryReader.ReadLittleEndianInt32();
            int height = binaryReader.ReadLittleEndianInt32();
            return new Size(width, height);
        }

        private static Size DecodeJfif(BinaryReader binaryReader)
        {
            while (binaryReader.ReadByte() == 0xff)
            {
                byte marker = binaryReader.ReadByte();
                short chunkLength = binaryReader.ReadLittleEndianInt16();

                if (marker == 0xc0)
                {
                    binaryReader.ReadByte();

                    int height = binaryReader.ReadLittleEndianInt16();
                    int width = binaryReader.ReadLittleEndianInt16();
                    return new Size(width, height);
                }

                binaryReader.ReadBytes(chunkLength - 2);
            }

            throw new ArgumentException(errorMessage);
        }
    }
}

```

And remember: **Try keeping the graphical and client-like code off the server where it's possible.** If you STILL Have the requirement in which you need to do per-pixel-collision, keep on reading.

If you're doing this because of cheating, you probably don't need to. Simple checks to make sure a player isn't blatantly cheating is always important - but for some things it just isn't worth it. If you're worried about players no-clipping, do generalized checks - not a pixel-perfect one. You can even use smaller bounding boxes, and it'll still be a lot cheaper.

You might already know all about masks, but I'm going to include a quick link here for reference. The main thing you really need to know here is that you should generate a *mask* for your objects if possible and use rectangles for a quick approximation check. This will significantly reduce load on your server where possible - and I think you'll need it!

In the end, it'll depend on your game requirements. Good luck!
> 4 votes

# Answer
Texture2D is more or less a class that sets how a particular graphics device draws a particular texture, with mip-maps and whatnot. If there is no graphics device...what is it doing exactly?

This said, you will need to save and store the textures in a slightly more manual way. Fortunately, .NET has libraries that allow for per-pixel manipulations through their own classes and structures. You should take a look at Microsoft's information on BitmapImage and BitmapSource. You still have access to individual pixels, so you can do calculations through CopyPixels().
> 0 votes

# Answer
You can create a `GraphicsDevice` and `ContentManager` without having a `Game`. I've already written about this in this answer \- I'll reproduce the code below, it uses some classes from the XNA WinForms sample. Basically all you need is a window handle (`Form.Handle`) to attach the graphics device to.

```
Form form = new Form(); // Dummy form for creating a graphics device
GraphicsDeviceService gds = GraphicsDeviceService.AddRef(form.Handle,
        form.ClientSize.Width, form.ClientSize.Height);

ServiceContainer services = new ServiceContainer();
services.AddService<IGraphicsDeviceService>(gds);
content = new ContentManager(services, "Content");

```

---

An alternative to this, which is probably *way* too much effort, is to load the texture yourself. The documentation for the XNB file format is here.

The biggest challenge in using this method is if your assets are built with XNB compression. You'd then either need a separate asset build for your server, without compression. Or you'd need to mess around with reflection to get access to the required decompression methods in XNA.

This method is preferred if you'd like your server to be able to run without a graphics device, as there are many circumstances - often the kind of scenarios where you'd like to run a server - where it's not possible to create a graphics device (or you "lose" the device during execution).
> 0 votes

---
Tags: xna, c#, graphics-programming, xna-content-pipeline, xna3.1
---


# Question
Title: DPad style movement for AI without using A*
What is the easiest way to implement DPad style movement (No diagonal) for AI without using and A\* algorithm? I thought about having the enemy catch up to the player in the Y axis first then the X axis (or vice versa) but then it would be too easy to evade the enemy. If it matters I'm doing this in Objective-C using Cocos2d. Any input would be appreciated.

# Answer
> 0 votes
For Orthogonal movement, you can choose randomly between the two directions you need to go.

The red player and blue enemy are in the world. They are separated by 2x and 3y or (2,3). So we know we need to move in both the X plus direction and the Y plus direction. So we choose randomly between the two. Say we choose the X plus direction, now they're separated by (1,3). Now say the random choice again chooses X plus direction. Now they're separated by (0,3). Now the only choice is to move in the Y plus direction.

Otherwise, move in the longest direction first, then the shortest. If you're worried about the player being able to too easily avoid the enemy make the enemy move slightly more often than the player. Say 1.1 moves per the player's 1 move.

---
Tags: cocos2d-iphone, ai, movement, objective-c
---


title: Phong lighting model unrealistic result

text:
# Question
Title: Phong lighting model unrealistic result
I am using OpenGL 2.1 and GLSL 1.20 .

I am trying to compute the fragment color applying the Phong lighting model.

This is the formula I have (the original formula has a summation, but since the light is only one it's not needed):

> Ip = Ka * Ia + Kd * (Lm • N) * Id + Ks * (Rm • V)^s * Is

With:

> Ka, Kd, Ks, s respectively material's ambient, diffuse, specular and shininess values;
> Ia, Id, Is respectively light ambient, diffuse and specular values;
> N surface normal;
> Lm direction vector point-light;
> Rm= 2.0 * (Lm • N) * N - Lm .

So this is the vertex shader:

```
#version 120

varying vec3 position; // I'll pass the position and the normal to
varying vec3 normal;   // the fragment shader
varying vec4 diffuse; // I'll compute here the ambient and diffuse
varying vec4 ambient; // values and pass them to the fragment shader

void main()
{
    gl_Position = ftransform();
    position= vec3(gl_Position);
    gl_TexCoord[0] = gl_MultiTexCoord0;

    normal= normalize(gl_NormalMatrix * gl_Normal);
    ambient= gl_FrontMaterial.ambient * gl_LightSource[0].ambient;
    ambient+= gl_LightModel.ambient * gl_FrontMaterial.ambient;
    diffuse= gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;
}

```

And this is the fragment shader:

```
#version 120

varying vec3 position;
varying vec3 normal;
varying vec4 diffuse;
varying vec4 ambient;

void main()
{
    gl_FragColor= ambient+diffuse;
    vec3 Lm= vec3(normalize(position-vec3(gl_LightSource[0].position)));
    vec3 V= vec3(normalize(-position));
    float LdotN= max(dot(Lm,normal),0.0);  // Since I'll use this two times
                                           // I compute it just once and reuse it
    vec3 Rm= 2.0* LdotN * normal-Lm;
    // First part of the formula: Kd * (Lm • N) * Id
    gl_FragColor+= gl_FrontMaterial.diffuse * LdotN * gl_LightSource[0].diffuse;
    // Second part: Ks * (Rm • V)^s * Is
    gl_FragColor+= gl_FrontMaterial.specular* pow(max(dot(Rm,V),0.0),gl_FrontMaterial.shininess)* gl_LightSource[0].specular;
}

```

The result is unrealistic, it seems like the specular light is not really applied:

I tried with a teapot and this is the result:

After changing the camera position (the teapot was covering the light):

I think it's ok.

# Answer
> 5 votes
I think there are at least three major problems:

* You do not normalise the interpolated `normal` vector in the fragment shader, therefore losing all the benefits of Phong shading because the resulting normal can have a length much smaller than 1.
* The `position` value you pass to the fragment shader is in *clip space*, but the vector `V` is computed using the eye position in *view space*. You cannot do the light calculations in different spaces; you should choose view space instead (*ie.* apply model-view to the vertex instead of model-view-projection). Also, make sure the light position is passed in view space, too.
* Your normal is most likely pointing outside the object; however `Lm` is computed as pointing from the light to the object; you should invert the sign of `Lm`.

# Answer
> 1 votes
\[Moved from comment on request and expanded.\] I don't know what the actual problem is, so here's some advice on troubleshooting lighting.

Are you sure the light position is such that the specular reflection should actually be visible on that (apparently) flat square? Most ‘shiny’ objects are curved and so have greater opportunities to have a visible specular ‘hot spot’.

I suggest instead testing with a sphere or other highly curved geometry to more completely display the effects of your lighting.

# Answer
> 1 votes
There is some problem in the shader program: 1) The normal must be normalized. 2) Change the direction of Lm 3)V should not be normalized as it is the position of vertex in camera space

Hope it will give you the correct result.

---
Tags: opengl, glsl
---


# Question
Title: Ways to represent/store different regions in a non tiled map
I am developing a game where agent tribes fight each other for land.The map is a 2D map.Each agent has an instance of group object that represents their family.And each group object contains information about the tribe.

Now the issue is how to store and represent the area each tribe owns.I was thinking of something along the lines of having the land split into own-able tiles of land and then having an ArrayList of Dimensions representing the region (width,height) and also storing positions alongside in order to know where the region starts from..Now the way tribes gather the land owned is as follows:

1. If the current square that agent is on is free then take the land
2. If not then if the current square is occupied try to fight it off from the other agent group

Now please note that actual agent movement is not based on tiles therefore I am not sure if my idea of representing the own able land as tiles is good for this.

So I am seeking on advice from anybody who has had a similar problem to deal with or have good ideas that they can share.

Also I am attaching an image to better explain my situation.

**NOTE: The rectangles of different colours represent the areas owned by the agents whereas the circles in different colours are the agents themselves.**

# Answer
> 3 votes
Could you please tell why you need to `store and represent the area each tribe owns`? Because I don't think it's necessary.

Simply put, you can just have a regular TileMap (some sort of 2D array), with each tile having an attribute 'ownedBy'. I think you don't actually need to have a datastructure which would represent all tiles owned by a certain group, because the 'ownedBy' attribute of a tile solves many issues:

* Rendering is simple, just iterate through all the tiles and check what color they should be. You can add fancy borders (like in your image) by checking the neighbours of each tile.
* Fighting over land is simple, since you're only interested in that one tile that the combatants are standing on (or maybe also it's neighbours).
* Score calculation is also simple, just iterate over the whole map and sum up how much every team owns.

So I think the simplest solution has you covered :) Unless I'm missing something.

Now, the other issue - `actual agent movement is not based on tiles therefore I am not sure if my idea of representing the own able land as tiles is good for this` \- this is not really a question about code organisation, but a question of visualisation. The same underlying data - that is, the tiles - can be displayed in different ways:

* With sharp borders and sharp corners, like in your example
* With sharp borders, but curvy corners - you try simple rounded corners (like the paint rectangle tool can do), or you can try getting fancy with Bezier curves.
* With fuzzy borders, but sharp corners - just put an alpha-map on the edges. You'll get something akin to tile transition techniques like this one.
* With fuzzy borders and curvy corners - some combination of the former two techniques. Get creative :)

If you find that it still looks like you're using tiles, maybe smaller tiles would help. Although you might need to implement fighting for many tiles at once if you make the tiles too small.

---
Tags: java, maps
---


# Question
Title: 2D Matrix Transformation (with a Player and Ground)
I have a simple game that I'm trying to do for learning purposes, but Matrices are a bit hard, especially in DirectX.

I currently have a tilesystem that renders tiles at the screen and a character position at the center (on startup)

When the player move to the left, the ground should move to the right so he's always at the center of the screen. I use a Sprite to transform the Tiles and the player, but having trouble because the ground is moving and the player stands still on the ground still positioned at the center.

This is a topdown 2D game so I only need to transform Position (and perhaps rotation)

My Camera class has this method:

```
D3DXMatrixTransformation2D(&View, NULL, 0, &Scale, &Center, D3DXToRadian(Rotation), &Position);

```

I've also tried (for the Camera):

```
D3DXMatrixTranslation(&View, Position.x, Position.y, 0);

```

then when I render the ground sprite I set it to transform to the camera, but the Player has it's own Matrix that I use when he's moving.

Exactly like the one above but with his position, rotation and such...

What am I missing and what do I need?

I only have a tilesystem that fits the width/height of the screen so I should see when he's moving but he's standing still at the center and the ground and the player is moving.

Do I need to invert the matrix so that the ground moves in the opposite direction?

# Answer
With the help of people at the chat I realized what the problem was with my system, altough I tried similiar things but probably in the wrong way / order.

For a simple 2D TopDown camera with just positioning:

Camera2D Translation:

```
D3DXMatrixTranslation(&CameraView, Position.x, Position.y, 0);

```

For each object in the camera's view:

```
D3DXMATRIX ObjectWorld;
D3DXMatrixTransformation2D(&world, NULL, 0, NULL, NULL, 0, &Position);

D3DXMATRIX Translation;
D3DXMatrixMultiply(&Translation, ObjectWorld, CameraView);

```

and then to render the sprite:

```
sprite->SetTransform(&Translation);
sprite->Draw(Texture, NULL, NULL, NULL, Color);

```

altough this method requires me to move the camera in the opposite direction that the player is moving, so if player is moving +100, the camera should move -100 to still be positioned at the same location relative to the camera, but it's also possible to Invert the matrix with

```
D3DXMatrixInverse();

```
> 0 votes

---
Tags: c++, directx, matrix, directx9, transformation
---


title: 2D XNA Shooting Game

text:
# Question
Title: 2D XNA Shooting Game
im doing a XNA game for a school project but im having trouble with the bullets. I can´t find any way to draw them or "invoque" them went i want. It is a modified Space Invaders that im trying to do. Sorry for my bad english. Help plz PS: im using rectangles instead of vectors.

# Answer
http://xbox.create.msdn.com/en-us/education/gamedevelopment

the tutorial here should be more than enough to see you on your way
> 1 votes

---
Tags: xna, c#, 2d
---


# Question
Title: Overlapping buttons with OpenGL and GLKit
I'm developing a game for iOS and I'm quite new to OpenGL.

I'd like to ask some help please, hoping that it could be useful to other people too.

At the moment I'm managing buttons simply by drawing textured 'quads' and detecting the user's tapping. I understand that in OpenGL objects are drawn in a sequential order, but I'd like to manage the visibility of the buttons independently from the order in which my buttons (and more in general objects) are drawn.

My question is: is there a not too complex way to accomplish that (without changing the alpha component, but assigning a certain 'depth' to objects for example)?

Here's my class that handles this (hope it's not too much code, but it's for the sake of clarity):

```
#import "Sprite.h"
#import <QuartzCore/QuartzCore.h>
#import <GLKit/GLKit.h>

typedef struct {
    CGPoint geometryVertex;
    CGPoint textureVertex;
} TexturedVertex;

typedef struct {
    TexturedVertex bl;
    TexturedVertex br;
    TexturedVertex tl;
    TexturedVertex tr;

} TexturedQuad;

@interface Sprite()

@property (strong, nonatomic) GLKBaseEffect     *effect;
@property (assign, nonatomic) TexturedQuad      quad;
@property (strong, nonatomic) GLKTextureInfo    *textureInfo;

@end

@implementation Sprite

@synthesize effect          = _effect;
@synthesize quad            = _quad;
@synthesize textureInfo     = _textureInfo;
@synthesize position        = _position;

@synthesize contentSize     = _size;
@synthesize moveVelocity    = _moveVelocity;

- (void)setupGeometry
{
    self.contentSize = CGSizeMake(self.textureInfo.width, self.textureInfo.height);

    TexturedQuad newQuad;
    newQuad.bl.geometryVertex = CGPointMake(0.0f, 0.0f);
    newQuad.br.geometryVertex = CGPointMake(self.textureInfo.width, 0.0f);
    newQuad.tl.geometryVertex = CGPointMake(0.0f, self.textureInfo.height);
    newQuad.tr.geometryVertex = CGPointMake(self.textureInfo.width, self.textureInfo.height);

    newQuad.bl.textureVertex = CGPointMake(0.0f, 0.0f);
    newQuad.br.textureVertex = CGPointMake(1.0f, 0.0f);
    newQuad.tl.textureVertex = CGPointMake(0.0f, 1.0f);
    newQuad.tr.textureVertex = CGPointMake(1.0f, 1.0f);

    self.quad = newQuad;
}

#pragma mark - Constructors

- (id)initWithLoader:(GLKTextureInfo * (^)(NSDictionary *))textureLoader andEffect:(GLKBaseEffect *)effect
{
    self = [super init];
    if (self)
    {
        self.effect = effect;
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], GLKTextureLoaderOriginBottomLeft, nil];
        self.textureInfo = textureLoader(options);

        [self setupGeometry];
    }
    return self;
}

- (id)initWithFile:(NSString *)fileName effect:(GLKBaseEffect *)effect
{
    return [self initWithLoader:^GLKTextureInfo *(NSDictionary *options) {
        NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];

        NSError *error;
        GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithContentsOfFile:path options:options error:&error];

        return textureInfo;
    } andEffect:effect];
}

- (id)initWithCGImage:(CGImageRef)image effect:(GLKBaseEffect *)effect
{
    return [self initWithLoader:^GLKTextureInfo *(NSDictionary *options) {
        NSError *error;
        GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithCGImage:image options:options error:&error];

        return textureInfo;
    } andEffect:effect];
}

#pragma mark - Screen functions

- (GLKMatrix4)modelMatrix
{
    GLKMatrix4 modelMatrix = GLKMatrix4Identity;
    modelMatrix = GLKMatrix4Translate(modelMatrix, self.position.x, self.position.y, self.Zindex);

    modelMatrix = GLKMatrix4Scale(modelMatrix, self.scaleFactor, self.scaleFactor, 1.0f);

    return modelMatrix;
}

- (void)render
{
    self.effect.texture2d0.name = self.textureInfo.name;
    self.effect.texture2d0.enabled = YES;
    self.effect.transform.modelviewMatrix = self.modelMatrix;
    [self.effect prepareToDraw];

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);

    long offset = (long)&_quad;
    glVertexAttribPointer(GLKVertexAttribPosition, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedVertex), (void *) (offset + offsetof(TexturedVertex, geometryVertex)));
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedVertex), (void *) (offset + offsetof(TexturedVertex, textureVertex)));

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

- (void)update:(float)seconds
{
    GLKVector2 curMove = GLKVector2MultiplyScalar(self.moveVelocity, seconds);
    self.position = GLKVector2Add(self.position, curMove);
}

@end

```

Thank you very much in advance.

# Answer
To draw things with transparency in OpenGL you will have to sort them by depth so you can render them in back-to-front order.

I would suggest that your render function create a list of all the textured quads to draw along with a depth value. Then sort the list. Then draw it.
> 1 votes

---
Tags: opengl-es
---


title: Fill texture with white color

text:
# Question
Title: Fill texture with white color
How to paint texture with white color? Example what I mean:

`SpriteBatch.setColor` changes tint only.

# Answer
> 3 votes
As indicated above, simply implementing a pixel shader to change the color would be sufficient. Other than that, you could swap out textures on the fly. That is a bigger performance hit though, by far.

---
Tags: opengl, opengl-es, libgdx, opengl-es2
---


# Question
Title: How to create an array of images on a canvas
I am developing a game that uses different images.When am image is swiped to the bottom of the screen it disappears and a new image appears at the top.Seeing as you can't delete an individual image I want to clear the canvas and redraw the images from an array of images. My question is how do you create an array that is accessible from the onDraw method?

# Answer
> 3 votes
This sounds like a simple scope issue. One method could be to implement a static management class that is responsible for the images. You could then get the data from this management class at any point in time. This allows you to encapsulate your data, and provide additional methods for manipulating your image data at will.

---
Tags: android, html-canvas
---


title: Line segment and Sphere intersect

text:
# Question
Title: Line segment and Sphere intersect
How can I check it if a line3D/ or ray is intersecting a sphere?

# Answer
The real time rendering web-site is good source for different intersection algorithms (including ray/sphere intersection):

http://www.realtimerendering.com/intersections.html
> 4 votes

# Answer
The problem logically reduces to finding the *shortest distance between the ray (line) and the sphere centre*. If that distance is shorter than the sphere radius, there is an intersection.

Of course, there's a formula for line-point distance.
> 4 votes

# Answer
It is a part of ray tracer design. Look at the ray and sphere intersection. It is very simple and commonly used in every ray tracer.
> 0 votes

---
Tags: collision-detection, mathematics
---