# Question
Title: Is it possible to use a spherical collision component in UDK?
I have an object in UDK, which has a `SkeletalMesh`. At certain times in the game, I want this object to continue rendering the `SkeletalMesh`, but I'd like it to use spherical collision temporarily.

After reading a bunch about `PrimitiveComponents`, my understanding is that UDK supports cylindrical and box-like collision, but not spherical without using a static mesh.

EDIT: What I have now is a `StaticMesh` with a material that makes it invisible. I've added a `StaticMeshComponent` to my `Pawns`. I can shut off the Pawn's collision, and turn on the StaticMesh collision. But it doesn't respond to impulses. I figure I'm missing something in how you turn on the RigidBody thingy.

```
CylinderComponent.SetActorCollision(false, false);
SetPhysics(PHYS_RigidBody);
RBCollisionComponent.SetStaticMesh(RBCollisionMesh);
RBCollisionComponent.AddImpulse(InImpulse);
RBCollisionComponent.WakeRigidBody();

```

# Answer
It turns out that I just needed to set the CollisionComponent of the Pawn to be the StaticMeshComponent, and set all the collision channels properly. Also, changing the StaticMesh to use simplified spherical collision helped.

```
CylinderComponent.SetActorCollision(false, false);
SetPhysics(PHYS_RigidBody);

CollisionComponent = RBCollisionComponent;
RBCollisionComponent.SetStaticMesh(RBCollisionMesh);
RBCollisionComponent.WakeRigidBody();
RBCollisionComponent.SetRBChannel(RBCC_Pawn);
RBCollisionComponent.SetRBCollidesWithChannel(RBCC_Default, true);
RBCollisionComponent.SetRBCollidesWithChannel(RBCC_Pawn, true);
RBCollisionComponent.SetRBCollidesWithChannel(RBCC_Vehicle, false);
RBCollisionComponent.SetRBCollidesWithChannel(RBCC_Untitled3, false);
RBCollisionComponent.SetRBCollidesWithChannel(RBCC_BlockingVolume, true);

```
> 1 votes

---
Tags: udk
---


# Question
Title: Problem animating in Unity/Orthello 2D. Can't move gameObject
I have a enemy npc that moves left and right in a corridor. It's animated with 2 sprites using Orthello 2D Framework.

If I untick the animation's play on start and looping, the npc moves correctly.
If I turn it on, the npc tries to move but is pulled back to his starting position again and again because of the animation loop.
If I turn looping off during runtime, the npc moves correctly again.

What did I do wrong?

---

Here's the npc code if needed.

```
using UnityEngine;
using System.Collections;

public class Enemies : MonoBehaviour
{
    private Vector2 movement;
    public float moveSpeed = 200;
    public bool started = true;
    public bool blockedRight = false;
    public bool blockedLeft = false;
    public GameObject BorderL;
    public GameObject BorderR;

    void Update ()
    {
        if (gameObject.transform.position.x < BorderL.transform.position.x)
        {
            started = false;
            blockedRight = false;
            blockedLeft = true;
        }
        if (gameObject.transform.position.x > BorderR.transform.position.x)
        {
            started = false;
            blockedLeft = false;
            blockedRight = true;
        }

        if(started)
        {
            movement = new Vector2(1, 0f);
            movement *= Time.deltaTime*moveSpeed;
            gameObject.transform.Translate(movement.x,movement.y, 0f);
        }
        if(!blockedRight && !started && blockedLeft)
        {
            movement = new Vector2(1, 0f);
            movement *= Time.deltaTime*moveSpeed;
            gameObject.transform.Translate(movement.x,movement.y, 0f);
        }
        if(!blockedLeft && !started && blockedRight)
        {
            movement = new Vector2(-1, 0f);
            movement *= Time.deltaTime*moveSpeed;
            gameObject.transform.Translate(movement.x,movement.y, 0f);
        }
    }
}

```

# Answer
Found the problem.
There was a change in orthello's version 2.4c (dirtychecks=false) that made gameObject.transform not work.
sprite.position should be used instead.

LINK
> 1 votes

---
Tags: 2d, unity, animation
---


title: Fixed texture size (Pixel) libgdx, java

text:
# Question
Title: Fixed texture size (Pixel) libgdx, java
If I resize the window (e.g. fullscreen) the texture size also changes!

I want that behaviour: If I change to fullscreen you will see more of the game world. The size (Pixel) of the texture stay the same. Not a scaling.

Thanks.

Regards, Matthias

# Answer
In your main `ApplicationListener` where you create a camera object there will also be a resize method. If not override/implement it. It takes two arguments and when the window is resized these will be the dimensions of the newly resized window. Just set the cameras size to the new window size and call `camera.update();` Should sort it! (I assume you are using the built in `OrthographicCamera` class of Libgdx)

Hope this helps
> 3 votes

---
Tags: java, camera, libgdx, pixel
---


title: SDL_image & OpenGL Problem

text:
# Question
Title: SDL_image & OpenGL Problem
i've been following tutorials online to load textures using SDL and display them on a opengl quad. but ive been getting weird results that no one else on the internet seems to be getting...

so when i render the texture in opengl i get something like this. http://www.kiddiescissors.com/after.png

when the original .bmp file is this: http://www.kiddiescissors.com/before.bmp

ive tried other images too, so its not that this particular image is corrupt. it seems like my rgb channels are all jumbled or something. im pulling my hair out at this point.

heres the relevant code from my init() function

```
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
    return 1;
}
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 );
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32, SDL_HWSURFACE | SDL_GL_DOUBLEBUFFER | SDL_OPENGL);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(50, (GLfloat)WINDOW_WIDTH/WINDOW_HEIGHT, 1, 50);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE);
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);

```

heres the code that is called when my main player object (the one with which this sprite is associated) is initialized

```
texture = 0;
SDL_Surface* surface = IMG_Load("i.bmp");
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, surface->w, surface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(surface);

```

and then heres the relevant code from my display function

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor4f(1, 1, 1, 1);
    glPushMatrix();
        glBindTexture(GL_TEXTURE_2D, texture);
        glTranslatef(getCenter().x, getCenter().y, 0);
        glRotatef(getAngle()*(180/M_PI), 0, 0, 1);
        glTranslatef(-getCenter().x, -getCenter().y, 0);
        glBegin(GL_QUADS);
            glTexCoord2f(0, 0);
            glVertex3f(getTopLeft().x, getTopLeft().y, 0);
            glTexCoord2f(0, 1);
            glVertex3f(getTopLeft().x, getTopLeft().y + size.y, 0);
            glTexCoord2f(1, 1);
            glVertex3f(getTopLeft().x + size.x, getTopLeft().y + size.y, 0);
            glTexCoord2f(1, 0);
            glVertex3f(getTopLeft().x + size.x, getTopLeft().y, 0);
        glEnd();
    glPopMatrix();

```

let me know if i left out anything important... or if you need more info from me.

thanks a ton,

-Dylan

# Answer
> 3 votes
This is my solution for SDL\_image to OpenGL RGBA texture. Last I tested, it works with everything except .xcf. The solution is simple, create a SDL\_PixelFormat and use SDL\_ConvertSurface..

```

SDL_PixelFormat pf;
pf.palette = 0;
pf.BitsPerPixel = 32;
pf.BytesPerPixel = 4;
pf.alpha = 255;
pf.Rshift = pf.Rloss = pf.Gloss = pf.Bloss = pf.Aloss = pf.colorkey = 0;
pf.Rmask = 0x000000ff;
pf.Gshift = 8;
pf.Gmask = 0x0000ff00;
pf.Bshift = 16;
pf.Bmask = 0x00ff0000;
pf.Ashift = 24;
pf.Amask = 0xff000000;

SDL_Surface* glSurface = SDL_ConvertSurface(imgSurface, &pf, SDL_SWSURFACE);

//convert width or height to nearest power of 2? you can but seems to work ok without it

//gen and bind

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, glSurface->w, glSurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, glSurface->pixels);

//tex parameters

SDL_FreeSurface(glSurface);

```

# Answer
> 0 votes
I notice the before.bmp file is 4-channel RGBA (32bpp), but you're telling OpenGL that the pixels you're passing are 3-channel RGB (24bpp). I'm not personally familiar with SDL\_Image, so it may be cleverly converting the pixel format at load time, but you could try changing the "GL\_RGB"s in your 2nd block of code to "GL\_RGBA" to see if that fixes things.

In general, you should check the pixel size of the image you loaded (surface-\>format-\>BytesPerPixel). If it's 3, use GL\_RGB when creating the texture; if it's 4, use GL\_RGBA. (It's actually more complicated than that, if you want to correctly handle all possible pixel formats, but that should be enough to get you started).

Also, you have blending enabled; is that really what you want? If you want the image displayed as you see it (no transparency/alpha), try removing these three lines:

```
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);

```

# Answer
> 0 votes
i didnt end up figuring out the scramble thing (which seem to only happened to images without transparency and when i was in plain RGB mode without Alpha)... but i did fix the weird tinting issue (mentioned in the comments section). the solution is below:

i was binding the texture to my object before drawing the quad, but not "unbinding" it after it had been rendered. i added

```
glBindTexture(GL_TEXTURE_2D, 0);

```

after the glEnd() call and as far as i can tell everything else in the scene is now normal using a .png file with transparency and in RGBA mode

---
Tags: c++, opengl, textures, sdl
---


# Question
Title: Best way to generate pieces in match-3 games, and then tracking them?
I've been working on a match-3 style game in Actionscript using Flixel, and so far, I've been able to build the core mechanics of the game, including board generation, piece generation, piece swapping and movement, and checking algorithms.

However, I am now running into issues with clearing out pieces and letting the above pieces fall down and generating new pieces.

The reason I'm running into these issues is that when all of the pieces are generated, the pertinent values (position, sprite ID, and sprite object) are pushed into an array that helps me track everything, all the time. When pieces are moved, I swap the values of the corresponding arrays and life goes on.

And that array is the core of my problem: if a row in the middle of the board clears out, ideally, all of the pieces above the cleared pieces should fall down to take their place and new pieces are generated at the top and also fall into place. Except if I try to do that now, all the pieces *can* fall down, but then I'd have to bump all of their values into the right arrays (oh god my head) and then generate new pieces and fit *THOSE* into the correct place in the array.

Am I overthinking this? Or is there a far better way to track these pieces?

Thanks guys!

# Answer
> 9 votes
As I said in the comments, a 2D array would probably help you out.
Lets say this is our 5 by 5 grid and we have a match

So we know 3 tiles will be removed, therefore we need to randomize 3 new values for 3 spots. The catch is however we first need to move the tiles in the same column that were above( blue ) the tiles that were removed (red). It would be easier to traverse from the bottom up ( highest index first to lowest). You can easily count how many tiles you need to move first based on the current index value of y|row to index value 0. You simply **copy** the value in order. So in the illustration at {3}{2} ( y index first then x) the tile value should receive the blue tile value. At this point we haven't tweened anything yet.
We know the amount of new tiles needed to fill the column so we simply generate new values and set the free spots to these values (you can do this from bottom up or the other way around ). You then simply create your visuals and tween them to the right position.

The position is calculated by the tile width and height.
For example if we take 32x32 and index column(x) = 2 and index roy(y) = 4.
The position = 64, 128.

When creating tile objects, it's easy to just store their position in them. So when you click on them you can just request their grid position. Don't forget to update this on every move.

If you set all these values into variables ( including the size of your 2D array ) you can easily resize your grid, visually and structurally.
Keep in mind that I'm trying to keep the actual data separate from my visuals. Eventhough they are in a way linked by their grid position. We simply have the sprites to click on them and request their position. ( you can do this without sprites though, by calculating the mouse position and converting it into a grid position). But the actual logic is done trough the 2D grid. We then simply call functions to move our visuals and set their new grid position.

I also have to mention, you need to do bound checking as you traverse trough your grid. You don't want out of bound exceptions ( going below 0, or above the capacity )

Hope this helps.

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


title: How Good Is The Xbox 360's Hardware?

text:
# Question
Title: How Good Is The Xbox 360's Hardware?
I'm thinking about doing things in XNA because I really like C# but I'm wondering about the whole Xbox 360 Development. How good exactly good will the hardware be, also I heard that the games are optimized for the hardware would that apply for XNA games?

As a side question does anyone know if you can release a XNA game in the XBLA?

# Answer
Well, besides the comment-answers, the 360 is powerful enough for whatever you want to do as long as you do it well. XNA is not truly optimized for the hardware but it does a pretty good job. And, yes you can release an XNA game to the XBLA provided you have a license with microsoft (which costs upwards of tens of thousands of dollars possibly). Most XNA games are released on the XBLIG (Indie games) channel.
> 1 votes

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


# Question
Title: Examples of 2D side-scrollers that achieve open non-linear feel?
I'm working on a 2.5D platformer prototype that aims for an open feel while maintaining familiar core mechanics.

Now, there's some obvious challenges with creating a non constricted feel in a spatially constricted environment. What I'm interested in, is examples of how game designers deal with the *"here's a level, beat the bad guys/puzzles to get to the next level"* design that seems so natural to most platformers (eg. Mario/Braid/Pid/Meat Boy to name a few).

Some ideas for achieving openness I've come across include:

* One obvious successful example is **Terraria**, which achieves openness simply through complexity and flexibility of the game-system
* Another example that comes to mind is **Cave Story**. Game is non-linear, offers multiple choices and side-stories
* **Mario**, **Rayman** and some other 'classics' with a top-down level selection. I actually really dislike this as it never did anything for me emotionally and just seems like a bit of a lazy way to do things.

Note: I've not actually had much experience with most of the 'classical' console platformers, apart from the obvious Marios/Zeldas/Metroids, since I've grown up on adventure games. By that I mean, it's entirely possible that I simply missed some games that solve the problem really well and are by some considered obvious 'classics'.

# Answer
> 1 votes
You mentioned Metroid in your last paragraph, but I would point to that game as the best example of an open-feeling 2D side scroller. Castlevania II also did this well (the others were more linear).

# Answer
> 1 votes
One of the best platformers I've ever played, Shadow Complex. They built a giant 2.5D environment, and put in events that advance a plot. But the player is utterly free to explore. A player receives "experience" perks from playing the game enough, such as unlimited special weapons and tools. And those allow a player even more freedom on subsequent playthroughs.

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


# Question
Title: XNA GUI: Creating a 'scroll pane' widget
I'm trying to create a simple GUI system and am currently stuck on how to implement a textarea with a scrollbar. In other words, the text is too large to fit into the view area. I want to learn how to do this, so I'd rather not use an already rolled API.

I believe this could be done if the text were part of a texture, but if the game had a lot of unique dialog, this seems expensive.

I researched creating a texture on the fly and writing to it, but came up with nothing.

Any suggested strategies would be appreciated. I believe it boils down to: text in a texture and how? Or something I have not thought of...

# Answer
> 1 votes
You've basically got two problems to solve here.

First of all, you need to **offset your text** \- so that it moves around based on where the scrollbar moves. You can do this by passing a transformation matrix to `SpriteBatch.Begin`, or simply adding and offset to the position when you call `SpriteBatch.Draw`.

Usually using a matrix is preferred, as you don't have to correctly pass the offset in multiple places.

The second issue to solve is to **clip your text**, so that it's not drawing outside of the box that you want to draw it in. You can achieve this by either setting a viewport or a scissor rectangle.

A viewport involves setting `GraphicsDevice.Viewport` (and setting it back when you're done). This affects drawing coordinates - `SpriteBatch`, for example, puts (0,0) at the top-left of the viewport.

Setting a scissor rectangle requires both setting `GraphicsDevice.ScissorRectangle` and creating and using a `RasterizerState` that has `ScissorTestEnable = true`. It does not affect coordinates - it simply clips.

(Rendering text to a render target and drawing that would work - but it's both complicated and relatively slow.)

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


title: Help needed throwing a ball in AS3

text:
# Question
Title: Help needed throwing a ball in AS3
I'm working on a flash game, coding on the time line. What I'm trying to accomplish is the following: With the mouse you swing and throw/release a ball which bounces against the walls and eventualy comes to point where it lays still (like a real ball). I allmost had it working, but now the ball sticks to the mouse, in stead of being released, my question to you is: Can you help me make this work and explain to me what I did wrong? You can simply preview my code by making a movieclip named 'circle' on a 550x400 stage.

```
            stage.addEventListener(Event.ENTER_FRAME, circle_update);

var previousPostionX:Number;
var previousPostionY:Number;
var throwSpeedX:Number;
var throwSpeedY:Number;
var isItDown:Boolean;
var xSpeed:Number   = 0;
var ySpeed:Number   = 0;
var friction:Number = 0.96;
var offsetX:Number  = 0;
var offsetY:Number  = 0;
var newY:Number = 0;
var oldY:Number = 0;
var newX:Number = 0;
var oldX:Number = 0;
var dragging:Boolean;

  circle.buttonMode = true;
  circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
  circle.addEventListener(Event.ENTER_FRAME, throwcircle);
  circle.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
  circle.addEventListener(MouseEvent.MOUSE_UP, released);

  function mouseDownHandler(e:MouseEvent):void
  {
      dragging = true;
      stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
      offsetX = mouseX - circle.x;
      offsetY = mouseY - circle.y;
  }

  function mouseUpHandler(e:MouseEvent):void
  {
      dragging = false;

  }

  function throwcircle(e:Event)
  {
      circle.x += xSpeed;
      circle.y += ySpeed;
      xSpeed *= friction;
      ySpeed *= friction;

  }

  function changeFriction(e:Event):void
  {
      friction = e.target.value;
      trace(e.target.value);
  }

    function circle_update(e:Event){

        if ( dragging == true ) { circle.x = mouseX - offsetX;
      circle.y = mouseY - offsetY; }

            if(circle.x + (circle.width * 0.50) >= 550){ circle.x = 550 - circle.width * 0.50; }
            if(circle.x - (circle.width * 0.50) <= 0){ circle.x = circle.width * 0.50; }
            if(circle.y + (circle.width * 0.50) >= 400){ circle.y = 400 - circle.height * 0.50;  }
            if(circle.y - (circle.width * 0.50) <= 0){ circle.y = circle.height * 0.50;   }
        }

    function clicked(theEvent:Event) {
    isItDown =true;
    addEventListener(Event.ENTER_FRAME, updateView);
    }

    function released(theEvent:Event) {
        isItDown =false;
    }

    function updateView(theEvent:Event) {
        if (isItDown==true){
            throwSpeedX =  mouseX - previousPostionX;
            throwSpeedY =  mouseY - previousPostionY;
            circle.x = mouseX;
            circle.y = mouseY;
        }
        else{
        circle.x += throwSpeedX;
        circle.y += throwSpeedY;
        throwSpeedX *=0.9;
        throwSpeedY *=0.9;
        }
        previousPostionX= circle.x;
        previousPostionY= circle.y;
    }

```

# Answer
> 1 votes
Tidy up your code first:

* use only one ENTER\_FRAME event (`circle_update`), and instead of adding/removing another listener, set a flag to true or false, e.g.:
    + replace `stage.addEventListener(Event.ENTER_FRAME, drag);` with `dragging = true;`
    + replace `stage.removeEventListener(Event.ENTER_FRAME, drag);` with `dragging = false;`
    + add in `circle_update` method: `if ( dragging ) { /*code from drag method*/ }`
* use descriptive names, `throwCircle` should me `moveCircle`. Also, because so far there's going to be only one circle, move the code from `throwCircle` to `circle_update`
* remove duplicated code, e.g. one of these lines: `xSpeed *= friction;` and `throwSpeedX *=0.9;`
* you are adding another listener `updateView` in every `clicked` method, but you never remove it.

---
Tags: flash, actionscript-3, mouse, release
---


# Question
Title: Blender multiple animations and Collada export
Say I have a simple mesh in Blender, with two keyframes, like so:

Then, another animation for the same mesh, also with two keyframes:

Theese animations worke fine in Blender and I can switch between them in the Dopesheet, where they are called "actions":

The problem arises, when i try to export this to the Collada format, for use in my game engine. The only animation/action that seems to be carried over, is the one currently associated to the mesh. Is it possible to export multiple animations/actions for the same mesh, to the Collada format?

# Answer
> 7 votes
The Collada exporter in blender does not support what Collada calls "animation clips", so only the current animation will be exported. You have a few options I can think of:

1. Fix the exporter (or convince someone to do it for you).
2. Write a script that loops through the actions and exports a new file for each action.
3. Use the NLA editor to create a track that has all the actions in sequence.
4. Export to another format that is easier to work with.

Obviously the first choice would be most appreciated by everyone else coming across this problem in the future.

# Answer
> 0 votes
since i'm not using blender i can only guess :)

but i think you would have to "bake" it into one single action, say you have the first animation from frame 1 to 10 and the second animation frame 20 to 30 or something and then define in the game engine where to start and stop!

sebastian, xsheetgames

---
Tags: blender, collada
---


title: Cannot find the Cocos2d templates

text:
# Question
Title: Cannot find the Cocos2d templates
I am about to upgrade to the last version of Cocos2d and would like to uninstall my current Cocos2d templates before installing the new one but cannot find the templates to delete.

I have looked at a number of web comments on this such as Uninstall Cocos2D ans another uninstall example but to no avail. However, I still see Cocos2d in my Xcode (4.5) framework. I have been searching my directories but cannot find it.

Is there anyone out there who can give me a hint where to find it so i can delete in?

# Answer
> 1 votes
I must admit I haven't visited the pages you link to, so I don't know where you have looked already, but on my machine they seem to be in $HOME/Library/Developer/Xcode/Templates

---
Tags: cocos2d-iphone, xcode
---


title: Group arrival steering

text:
# Question
Title: Group arrival steering
I've got group movement implemented pretty much like this:

http://www.red3d.com/cwr/steer/CrowdPath.html

Basically, that's combining path following and separation. It works nicely as long as units are in transit, but arrival does not work very well at all.

Right now, units just cease to use the path following component once the "exit" the path, i.e. when their closest point on the path is on or past the end.

This leads to those units bumping into each other and also overshooting the point the player clicked. Ideally, I'd have the units arrive scattered around the finish point (and reasonable close to each other), not all clumped up past the finish line.

I'd imagine that some kind of arrival steering might work here, but based on other units and a "fuzzy" classification of the end of the path.

Is there any proven way to do this?

# Answer
1. Shorten the last part of the path by the radius of the area the units will occupy when they stop moving. You can guesstimate this based on the 2d size of the units and their number. Increase this approximation by 1.4-1.7x to prevent overlapping.
2. Randomize n points that do not overlap around in the destination where they will stand.
3. Sort the points by their distance from the last point on the path.
4. When the nth unit arrives at the end of the path, move it in a linear path to the nth most distant point in the collection you randomized and stop them. ie : The first will stand at the most distant point, the second at the 2nd most distant.
5. You should now have them standing scattered around the destination.

In order to randomize points that do not overlap and are not organized, take the destination and split it into spots for 2 or 3n units and then remove spots randomly.

I added some images for illustration:
> 1 votes

# Answer
You can combine multiple steering behaviors to get the result you want. You'll want to implement the arrival behavior. And combine it with the flocking behavior.

Select a "lead" unit. Whichever unit is in the lead works well. When you're using arrival, the arrival point for all other units in the group will be the lead unit position. The lead unit will be using the destination as it's arrival point. This will be sort of like a follow the leader situation. The lead unit will arrive at the destination and the other units will attempt to approach the lead unit.
> 1 votes

# Answer
You say you already have code to let the units avoid each other while in transit, so why not just keep that part of the code active even after reaching the goal?

In fact, to keep the units from clustering too tightly at the destination, you may want to increase the preferred separation for each unit as they reach the goal, so that they'll move out a little and give room for new arrivals.
> 1 votes

---
Tags: path-finding, steering-behaviors
---


# Question
Title: How to get a Read-Write Reference to Parent GameObject from a script component attached to it?
I have a game object(object) with a script component(myscript) attached.

I have a reference to myscript component through getComponent, and I want to change the transform of the gameObject the script is attached to.

```
myscript.gameObject.transform = (new value);

```

The above code gives me error,

> Property 'UnityEngine.GameObject.transform' is read only.

Is there a way to get a read-write version?

# Answer
> 2 votes
Transform is **read-only** C# property. I guess it could be defined pretty most this way:

```
public Transform transform{get;}

```

So, you can't assign directly a `Transform` to another `Transform` (you don't have set accessor defined). You are forced to assign individual fields of each `Transform` to the other.

For example:

```
myscript.gameObject.transform.rotation = otherScript.gameObject.transform.rotation;
myscript.gameObject.transform.position = otherScript.gameObject.transform.position;
...

```

# Answer
> 1 votes
If by "change the transform" you mean "change position/rotation/scale" of my object, you have to change these individually:

```
gameObject.transform.position = ...;
gameObject.transform.rotation = ...;
gameObject.transform.localScale = ...; // note that you CAN'T change global scale, as it's not actually a vector

```

If by "change the transform" you mean "change my object's parent", you have to change `parent` propery:

```
gameObject.transform.parent = someOtherTransform;

```

---
Tags: unity
---


# Question
Title: Side scroll game with 8000xScreen_Height, which technique is best
I got one new requirement for iOS side scroll game with screen size : 8000xScreen\_Height

For this, tileMap is best or normal texture based is best? I need to use parallax background too.

Help me to find right technique.

Thanks in advance.

# Answer
* I will talk how I render those things in my game.

My background (parallax) is divided in four segments. The game starts with the three segments on the screen, but as the player moves forward, the forth start showing up and the first starts disappearing (in the left side). Once it completes disappear, I move that segment to the front, and keep doing it. Basically, an infinite loop with four segments. The smaller the segments, less draws you do offscreen and faster draw times.

For the platforms I just create a big circle around my character, and if the "tile" is in this circle, then I render it, otherwise, ignore. It's a very fast radius distance check ;)

Personal opinion: I used my own level design tool to create the game level, where I used normal texture with variant objects size. But, if I were to do it again, I would use tileMaps, just because its simplify a lot of math and implementations.
> 4 votes

---
Tags: game-mechanics, cocos2d
---


title: Car Modelling for race game

text:
# Question
Title: Car Modelling for race game
I am taking Computer Graphics course this semester and we have a video game competition. I am making racing game with simulated dynamics. Our professor told us that we don't have to do much of a modelling but since we haven't started the gaming part and since I have free time I want to model the car.

My question is firstly which software do you recommend to design game components? I know Maya right now. Secondly, if I design the car or any other part, what should its polygon count in order to run game smoothly? I can design pretty much everything but I assume that it is hard to design low-poly models.

# Answer
> 3 votes
Maya should be fine for the purpose. Some people like to use Max for games instead, but if you know Maya, stick to that.

As to your second question - as long as you only have one (or a few) models, you can stick to a simple rule of thumb. Don't add any polygons that you don't need. By that I mean that if you have a more or less flat surface, and it's split into polygons, and these polygons are not important to your edge loops, then you're doing something wrong.

If you have no idea what an edge loop is, you should read about it. Good luck with your game!

# Answer
> 1 votes
Since you know Maya, go with it since it'll reduce your learning curve. You can also export to pretty much any format from Maya so you're sure you'll have something your code can read.

As for the poly count, it really depends on your hardware and the efficiency of your code. However, you shouldn't be reaching any practical limits on a project of this size so I'd go all out and make the model exactly as you want. You can reduce the poly count or adjust other stuff after you've ran test on your engine.

---
Tags: game-design, models, maya
---


title: multi-thread in mmorpg server

text:
# Question
Title: multi-thread in mmorpg server
For MMORPG, there is a tick function to update every object's state in a map. The function was triggered by a timer in fixed interval. So each map's update can be dispatch to different thread. At other side, server handle player incoming package have its own threads also: I/O threads. Generally, the handler of the corresponding incoming package run in I/O threads. So there is a problem: thread synchronization. I have consider two methods:

1. Synchronize with mutex. I/O thread lock a mutex before execute handler function and map thread lock same mutex before it execute map's update.
2. Execute all handler functions in map's thread, I/O thread only queue the incoming handler and let map thread to pop the queue then call handler function.

These two have a disadvantage: delay. For method 1, if the map's tick function is running, then all clients' request need to waiting the lock release. For method 2, if map's tick function is running, all clients' request need to waiting for next tick to be handle.

Of course, there is another method: add lock to functions that use data which will be accessed both in I/O thread & map thread. But this is hard to maintain and easy to goes incorrect. It needs carefully check all variables whether or not accessed by both two kinds thread.

My problem is: is there better way to do this? Or from practical view, the delay can be accepted because nothing will happen between 2 tick (the world is driven by continuous tick, all object will paused in 2 tick's interval) Generally, the interval is about 50ms to 100ms

Notice that I said map is logic concept means no interactions can happen between two map except transport. I/O thread means thread in 3rd part network lib which used to handle client request.

# Answer
> 0 votes
> I have consider two methods: Synchronize with mutex. I/O thread lock a mutex before execute handler function and map thread lock same mutex before it execute map's update.

If you do this, then there is hardly any point having separate threads, because only one runs at a time!

> Execute all handler functions in map's thread, I/O thread only queue the incoming handler and let map thread to pop the queue then call handler function.

This seems closer to what you should do. The I/O thread should handle I/O - nothing more. It needs to be able to get exclusive access to the message queue or data buffers that let the network exchange data with the game, and that's all.

You would not have 1 single lock for your entire map. Each client has its own lock (or locks), guarding its input and output. Only when that client is sending data or receiving it would you need to lock it.

> Of course, there is another method: add lock to functions that use data which will be accessed both in I/O thread & map thread. But this is hard to maintain and easy to goes incorrect. It needs carefully check all variables whether or not accessed by both two kinds thread.

This is not actually difficult at all. The answer is to make the shared data as small as possible. For example, use 2 queues, one for messages coming in (network -\> server) and one for messages going out (server -\> network). Lock the queue to add or remove messages, and ensure there is no other data shared across the I/O and logic sections.

# Answer
> 2 votes
Here's an architecture you might want to consider:

You might want to use separate processes for these tasks:
\- User authentication
\- Realm selection
\- Each realm (maybe broken into independent maps)
\- Ingame subtasks, such as mail/global chat subsystem, item/npc cache, largely independent of other state, that does not need to further burden the map server.

Using different processes ensures that a faulty module won't bring down the whole system. Partial reboot's and hot swapping's inherently supported. It's easier to scalate this model to several different machines if your needs require it.

Each module's internal architecture's very similar: Your input threads just push messages into a queue. Your core module requests this list each update, and feeds its messages to the message consumers. These message consumers run the required actions through transactions - acquire locks on affected objects (player inventory, pickable item), run actions (pick item), free locks. Outbound messages are queued in a message consumer local queue, so no synchronization's required here. Once all incoming messages have been processed, these thread local queues are harvested, merged and its messages forwarded to their respective targets.

# Answer
> 1 votes
You can run your IO on background threads that just waits for a full wellformed packet to come in, and then puts the data in the packet into a queue for the main processing thread to process. The main thread can run in a small while loop like:

```
while(!shutdown)
{
    dequeue_player_input();
    process_objects();
}

```

In general a multi-process instead of a multi-thread approach will better suit an MMO design. On MMO's I've worked on, a single process could handle anything from the entire world to a 20x20 meter square of the world. And as player and NPC concentration increased, the server would spin up other processes to handle smaller and smaller pieces of the world. IE: Maybe we'd start with 100 processes spread over 15 machines for the world, then 5000 players would come to see an event in one spot. That one spot alone would be handled by 16 processes none of them guaranteed to be on any single machine.

# Answer
> 0 votes
> Break down I/O threads and map threads into DP algorithms.

* Quad/Oct-Trees are good just because they are simple.
* Structure with moving objects (AABB), without having to rebuild a big part of the structure for each object
* Depending on the amount of reliable packets you want to send and the pace of the RPG TCP should be fine. A lot of networking libraries implement TCP basically with UDP allowing reliable/unreliable packets.
* Have a deep study on Synchronization architecture of Croquet Project will help you for better understanding.

# Answer
> 0 votes
I use 2 from your suggested solutions; because my server is c#, this is can be handled very nicely with a lock-less queue of WorkItems which contain a delegate and an array of parameters.

The thread which processes WorkItems can be asleep until a message arrives from the client, or it can always process messages at a update fixed interval. Works very well for me.

---
Tags: mmo, server, multithreading
---


# Question
Title: what does AngleVectors method in quake 3 source code does
I just downloaded quake 3 for learning purposes.
I know some of some linear algebra(basic vector math ie: dot,cross product).
However I can't decipher what below method does, I know what is yaw,pitch and roll.
But I can't connect these with vector.
Worse, I'm not sure this fall under what math 'category', so I don't really know how to google.
Hence the question here.
Anyone?

```
void AngleVectors( const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) {
float       angle;
static float        sr, sp, sy, cr, cp, cy;
// static to help MS compiler fp bugs

angle = angles[YAW] * (M_PI*2 / 360);
sy = sin(angle);
cy = cos(angle);
angle = angles[PITCH] * (M_PI*2 / 360);
sp = sin(angle);
cp = cos(angle);
angle = angles[ROLL] * (M_PI*2 / 360);
sr = sin(angle);
cr = cos(angle);

if (forward)
{
    forward[0] = cp*cy;
    forward[1] = cp*sy;
    forward[2] = -sp;
}
if (right)
{
    right[0] = (-1*sr*sp*cy+-1*cr*-sy);
    right[1] = (-1*sr*sp*sy+-1*cr*cy);
    right[2] = -1*sr*cp;
}
if (up)
{
    up[0] = (cr*sp*cy+-sr*-sy);
    up[1] = (cr*sp*sy+-sr*cy);
    up[2] = cr*cp;
}
}

```

ddddd

# Answer
> 1 votes
It just computes a (slightly wacky, because of Quake's "entity pitches are negative" thing) 3x3 rotation matrix, with each column (or row, depending on your preference) being one of the forward/right/up vectors. This can then be used to position various objects/effects/etc relative to the view; Quake uses it for pushing muzzleflashes slightly forwards and for sprite billboarding, for example.

Compare with the matrix described at http://blogs.msdn.com/b/mikepelton/archive/2004/10/29/249501.aspx

# Answer
> 1 votes
The function takes angles and calculates vectors that point in directions relative to `angles`.

For angles, and the operations `sin` `cos` and `tangent`, you'll want to look up trigonometry.

Multiplying an angle in degrees by `M_PI*2 / 360` converts degrees to radians. (M\_PI = 3.14).

`forward` is a vector that points in the direction that the angles form to create the forward facing direction.

`right` is a vector pointing to the right of where the `angles` representation is facing, and \`up' points directly up.

If `angles` represented the angles that you are looking at currently (i.e. your head), `forward` would point straight ahead of you, `right' would point to your right, and`up\` would point up from where your head is oriented.

---
Tags: vector, angles, quake3
---


# Question
Title: How to get tilemap transparency color working with TiledLib's Demo implementation?
So the problem I'm having is that when using Nick Gravelyn's tiledlib pipeline for reading and drawing tmx maps in XNA, the transparency color I set in Tiled's editor will work in the editor, but when I draw it the color that's supposed to become transparent still draws.

The closest things to a solution that I've found are -

1) Change my sprite batch's BlendState to NonPremultiplied (found this in a buried Tweet).

2) Get the pixels that are supposed to be transparent at some point then Set them all to transparent.

Solution 1 didn't work for me, and solution 2 seems hacky and not a very good way to approach this particular problem, especially since it looks like the custom pipeline processor reads in the transparent color and sets it to the color key for transparency according to the code, just something is going wrong somewhere. At least that's what it looks like the code is doing.

```
TileSetContent.cs
    if (imageNode.Attributes["trans"] != null)
        {
            string color = imageNode.Attributes["trans"].Value;
            string r = color.Substring(0, 2);
            string g = color.Substring(2, 2);
            string b = color.Substring(4, 2);
            this.ColorKey = new Color((byte)Convert.ToInt32(r, 16), (byte)Convert.ToInt32(g, 16), (byte)Convert.ToInt32(b, 16));
        }
        ...

TiledHelpers.cs
    // build the asset as an external reference
            OpaqueDataDictionary data = new OpaqueDataDictionary();
            data.Add("GenerateMipMaps", false);
            data.Add("ResizetoPowerOfTwo", false);
            data.Add("TextureFormat", TextureProcessorOutputFormat.Color);
            data.Add("ColorKeyEnabled", tileSet.ColorKey.HasValue);
            data.Add("ColorKeyColor", tileSet.ColorKey.HasValue ? tileSet.ColorKey.Value : Microsoft.Xna.Framework.Color.Magenta);
            tileSet.Texture = context.BuildAsset<Texture2DContent, Texture2DContent>(
                new ExternalReference<Texture2DContent>(path), null, data, null, asset);
       ...

```

I can share more code as well if it helps to understand my problem. Thank you.

# Answer
What I would do is open the tiles in an image editing program (like GIMP), and select all of that pink layer and delete it, leaving only a transparent background layer. Then no more worrying is necessary about using those tiles with colored backgrounds.
> 1 votes

---
Tags: xna, tilemap, xna-content-pipeline
---


title: Drag Gestures - fractional delta values

text:
# Question
Title: Drag Gestures - fractional delta values
I have an issue with objects moving roughly twice as far as expected when dragging them.

I am comparing my application to the standard TouchGestureSample sample from MSDN.

For some reason in my application gesture samples have fractional positions and deltas.

Both are using same Microsoft.Xna.Framework.Input.Touch.dll, v4.0.30319.

I am running both apps using standard Windows Phone Emulator.

I am setting my break point immediately after this line of code in a simple Update method:

```
GestureSample gesture = TouchPanel.ReadGesture();

```

Typical values in my app:

```
Delta = {X:-13.56522 Y:4.166667}
Position = {X:184.6956 Y:417.7083}

```

Typical values in sample app:

```
Delta = {X:7 Y:16}
Position = {X:497 Y:244}

```

Have anyone seen this issue? Does anyone have any suggestions?

Thank you.

# Answer
> 0 votes
Fractional values were caused by IsFullScreen set to false:

```
_graphics = new GraphicsDeviceManager(this)
                {
                    IsFullScreen = false, // Setting to true will make gesture deltas integer.
                    PreferredBackBufferWidth = 480,
                    PreferredBackBufferHeight = 800
                };

```

There is no visual difference between using fractional and integer values.

The bug with multiplied movement was caused by incorrect calculations inside my engine.

---
Tags: xna, xna-4.0, touch, gestures
---


# Question
Title: Alternatives to multiple sprite batches for achieving 2D particle system depth
In my 2D XNA game, I render all my sprites with a single sprite batch using `SpriteSortMode.BackToFront` and `BlendState.AlphaBlend`.

I'm adding a particle system based on the App Hub particles sample. Since this uses `SpriteSortMode.Deferred` and `BlendState.Additive`, I will need to have two `SpriteBatch.Begin` / `SpriteBatch.End` pairs: one for 'regular' sprites, and one for particles.

In my top-down shooter, If I want to have explosions appear under planes, but above the ground, then I believe I will have to have three `Begin`/`End` pairs, first to draw everything under the explosions, then to draw the explosions, then to draw everything above the explosions. If I want to have particle effects at multiple different depths, then I'm going to need even more `Begin`/`End`pairs.

This is all easy to code, but I'm wondering if there is an alternative way to handle this?

# Answer
> 1 votes
Try to render the first batch with SpriteSortMode.FrontToBack and DepthStencilState.Default

Then render the particles with SpriteSortMode.Deferred, BlendState.Additive and DepthStencilState.DepthRead...

I think it should works...

# Answer
> 0 votes
You are not specifying whether you are using entity component system or not. However, there is another way of approaching the problem instead of trying to solve it directly on top of the underlying toolkit.

Either case, if you have Artemis-like entity component system(ECS) available, you can easily achieve this layering by having individual component system for each layer. These layers, then automatically get called in right order and the entities drawn on screen will appear as specified.

```
BackgroundSystem backgroundSystem = new BackgroundSystem(0, world);
ExplosionSystem explosionSystem = new ExplosionSystem(1, world);
PlaneSystem planeSystem = new PlaneSystem(2, world);

```

In this example, lower number in the constructor means being drawn earlier. Now when these systems are added to the ECS, and the render is done, their render functions will be called in the specified order rendering background on the bottom, explosions on top and planes on top of explosions.

If you don't want to submit to using ECS, you can achieve similar by wrapping your SpriteBatch in a class, for example `Renderer` that implements rendering queue, and abstracting your rendering code into `Drawables` or something similar.

Each `Drawable` has a member `layer`, which acts as a hint to the `Renderer`. This can be an `enumeration` or an `integer` that is used to sort all `drawables` so that once rendering is done, they are drawn from bottom to top.

The good thing about this is that you can hide details of each drawable or component and simplify your rendering code.

---
Tags: xna, 2d, sprites, particles
---


title: MonoGame: PC + Mobile?

text:
# Question
Title: MonoGame: PC + Mobile?
I'm researching Monogame. Their goal is to allow "easy" porting of an existing XNA/Windows game to mobile.

Does this mean you can have one solution (theoretically) with shared code, and it works on all three platforms (PC, Android, iPhone)? Or do you need to port your game from PC to Android, and then again to iPhone?

I'm sure "write once, run anywhere" works 80% of the time, I'm not worried about that other 20% like support for GPS, acceleratometer, etc. which doesn't exist on all platforms.

# Answer
> 2 votes
You can keep all your code in one solution and most of the code will only have to be written once and work on all platforms.

Here's the catch, you need to create a new project per platform. For example you might have YourGame.Core, YourGame.Android and YourGame.Windows. Code that is shared between projects can live in the Core project and be added to the platform specific projects as linked files. It's a bit a maintenance pain, but not as much as you might think. Many developers have reported that they setup a project for a new platform in around 15 minutes once they have the windows one working.

The reason for this pain stems back to the ability to have a single project targeting multiple frameworks. For example, you can create a project that targets Mono / .NET 4 and a different project that targets Android 2.2. Each project can contain identical code, but there's currently no way to target both frameworks at the same time within the same project.

This problem is not isolated to Mono and has also been reported when people are developing for Microsoft specific platforms like Windows Phone and Silverlight.

http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2051965-allow-a-project-to-target-multiple-frameworks-ful

There is a better solution in the works called Portable Class Libraries. The idea is that you can have all of your core code in a single project and simply reference the DLL in each of your other projects.

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

It looks like Mono has at least partial support for Portable Class Libraries according to the Mono 3.0 release notes, but I haven't tried it yet.

http://www.mono-project.com/Release\_Notes\_Mono\_3.0#Smaller\_Updates

---
Tags: xna, monogame
---


# Question
Title: How do I autogenerate gradient lighting?
I am trying to think of a way to generate a gradient like this picture:

Something like this `GetGradientTexture(360f,100(width),100(height))`, or if i want a directional light (like a flashlight) `180f,10,200`.

But I can't really think of a good way to do this. Does anyone have anything that can push me in the right direction?

# Answer
> 1 votes
To do that circular type of gradient you can just take the length from the "Point" by doing. this code gives you a straight gradient.

```
vec1 = [ 1, 1, 1 ]; // this is your start point.
vec2 = [ 2, 2, 2 ]; // this is your endpoint.
vec3 = vec1 - vec2;
grad = sqrt(dot(vec3,vec3));

```

and if you want to other ways of gradient, you most of the time only calculate lengths.

And a directional light is not like a flashlight, or well, not meant to be use like that. A Spotlight is more like a flashlight. (With a light cone, and falloff ) The directional lighte is more like a "Global sun light".

---
Tags: xna, lighting
---


# Question
Title: How can I plot a radius of all reachable points with pathfinding for a Mob?
I am designing a tactical turn based game. The maps are 2d, but do have varying level-layers and blocking objects/terrain. I'm looking for an algorithm for pathfinding which will allow me to show an opaque shape representing all of the possible max-distance pixels that a mob can move to, knowing the mob's max pixel distance.

Any thoughts on this, or do I just need to write a good pathfinding algorithm and use it to find the cutoff points for any direction in which an obstacle exists?

# Answer
> 6 votes
Start of with the simplest pathfinding algorithm (I believe) Breadth-first search:

This is actually a very good algorithm if you want to find the best possible path, especially if various tiles have different movement ratios (how much movement points it costs to enter/leave the tile, e.g. mountain could take 3 points and road only 1/3). Because you have a limited movement, your BFS will end pretty quickly, most probably letting you calculate paths for one unit in a single frame without FPS drop below 60.

For an algorithm below I'll assume a little harder scenario, where there are various movement costs of tiles.

**Here's the recipe:**: You will need:

* the value representing how far you can go, named `movement_points`
* one dictionary of tile:movement\_points\_to\_reach\_it pairs named `costs`
* one list of `tiles_to_check`
* one list of `tiles_being_checked`
* starting tile, for which you check possible paths, let's name the tile a `hero`.

Let's make the cake:

1. Add `hero` to `tiles_to_check`
2. Initialize boolean `changed` variable with `true`
3. Start While (changed) loop.
    1. `changed = false;`
    2. `tiles_being_checked = tiles_to_check;`
    3. Assign new Array to `tiles_to_check`.
    4. Iterate through all `tiles_being_checked`
        * iterate through all tiles surrounding the current tile being checked and run a `processTile` function:
        * `t=tiles_being_checked[i]; for(x=t.x-1; x<=t.x+1; x++) for(y=t.y-1; y<=t.y+1; y++) if (x!=t.x || y!=t.y) processTile(t, x, y)`

**In processTile(tile, x, y) do:**

1. `next_tile = world_grid[x][y];`
2. Check if `next_tile` is passable, e.g. it's not a water tile. (if yes, return)
3. Check the cost of moving from `tile` to the `next_tile` and save it as `cost`; (take care of if it's diagonal movement - multiply by square root of 2 - and what's this/next tile's movement cost.
4. `total_cost = costs[tile] + cost;`
5. **Check if there are enough movement points to reach it:** `if (total_cost > movement_points) return;`
6. Check if there already exists this tile (as a key) in your `costs` dictionary, and if yes, check if you already found a better or equal way for this tile: `if (costs[next_tile] <= total_cost) return`
7. If not, write the new cost `costs[next_tile] = total_cost`
8. add `next_tile` to `tiles_to_check`
9. set `changed = true`.

**In the end use `costs` dictionary to check if a tile can be reached** by given movement points (it exists as a key in the dictionary) and to check how much movement points it will cost. To check for the path:

1. Choose a destination tile (that can be reached)
2. Set `currentX = tile.x; currentY = tile.y;`
3. Set `cost = MAX_INT;`
4. Create an Array of tiles `path = new Array ();`
5. start `while ( currentX != startTile.x || currentY != startTile.y )` loop.
    1. Iterate through neighboring tiles...
    2. ... and if a given neighboring tile, let's name it a `nTile` has lower cost than current: `if (costs[nTile] < cost) { cost = costs[nTile]; currentX=nTile.x; currentY=nTile.y;`
6. Reverse the array.

---
Tags: 2d, ai, path-finding, rpg
---


# Question
Title: What is the current state of 2D game SDK's
There seem to be so many to choose from.

* SDL
* Cocos2D-x
* Cocos2D-iphone
* Corona
* Unity

I am having a very hard time looking these over to decide why I want to use one over the other.

Advice on what and why?

# Answer
Well, is difficult to answer you question because is too wide. But here are the basics on each framework, as far as i know at least xD

* SDL - no idea, never used
* cocos2d-x - is basically a c port (has other options) from cocos2d-iphone. The main feature is cross platform, and they take this seriously, trying to provide support for every mobile OS out there. Is also the most stable side version of cocos2d. Needs c knowledge. Free.
* cocos2d-iphone - one of the most used framework for 2d games on the iOS market, is really simple and works amazing. The bad thing is that is only for iOS. Needs Objective-c knowledge. AMAZING community. Free.
* corona - never used but is a cross platform framework that works pretty well, has a rally good community and years on the market. Has lots of modules/features that makes the framework very easy to use and add features to your app/game. Needs Lua (scripting) knowledge. Paid (if i remember well).
* unity - first of all unity is not a framework is an engine, so based on that premise is really different from the others in the list. Of course is paid (i think that is free for 2d games but i don't exactly know). Cross platform, good community, bla bla. Is big, really big but as far as i know easy to learn. It was ment to be a 3d engine it supports 2d very well, with good libraries/modules that works pretty well.

So, it all depends on your needs, if you want to go cross platform or not, how big is your game, how much money you have, etc, etc. All the above frameworks are really good, but require different amount of work from your side.
> 1 votes

---
Tags: cocos2d-iphone, corona-sdk
---


# Question
Title: How to normalize the direction to check if the player is able to move?
I have a room with 4 walls along the x and z axis respectively. My player, who is in first person (therefore the camera), should have collision detection with these walls. I'm relatively new to this so please bare with me. I believe the way to do this is to calculate the direction and distance to the wall from the camera and then normalize the directions. However, I can only get this far before I don't know what to do. I think you should work out the angle and direction your facing?

Here `_dx` and `_dz` is the small buffer in front of the camera.

```
float CalcDirection(float Cam_x, float Cam_z, float Wall_x, float Wall_z)
{
    //Calculate direction and distance to obstacle.
    float ob_dirx = Cam_x + _dx - Wall_x;
    float ob_dirz = Cam_z + _dz - Wall_z;
    float ob_dist = sqrt(ob_dirx*ob_dirx + ob_dirz*ob_dirz);

    //Normalise directions
    float ob_norm = sqrt(ob_dirx*ob_dirx + ob_dirz*ob_dirz);
    ob_dirx = (ob_dirx)/ob_norm;
    ob_dirz = (ob_dirz)/ob_norm;

```

Can anyone explain in layman's terms how I work out the angle?

# Answer
This is actually a well documented problem. What you want isn't the distance from the camera to a specific point on the wall `(Wall_x,Wall_z)`. Rather, you can find the point on a wall which is closest to the camera, at any time. This article should tell you all about the math involved, even though it's for ActionScript.

Once you know the point which is closest, finding the distance and direction is trivial. Actually, you can look at the whole thing as collision detection between a circle (around the camera) and a line (a wall) in 2D (seen top-down, ignoring the y dimension).
> 1 votes

---
Tags: 2d, collision-detection, mathematics
---


# Question
Title: Single and Double Jump with single button.
I want to make Single Jump on Single Tap and Double Jump on Double Tap. My problem is that if I make double Tap on ground then it’s fine but if I make first Tap on ground and second Tap in Air then Player gain more height then usual As in image 1.

I want to Make my jump like in Image 2, No matter from which point user gives second Tap, player Always get a specific height.

I Used both Impulse and Linear velocity to make Jump but my problem did not solved.

# Answer
This really depends on how you want to implement the mechanic. For me, a common "double jump" would be a second jump in mid air, if you're still on your way up. As such, I'd probably do something like this:

```
// dY is my vertical velocity; positive is pointing upwards
if (keyTapped(JUMP)) {
    if (onGround()) {
        dY = 10;
        doubleJumped = false;
    }
    else if (dY > 0 && !doubleJumped) {
        dY = 10; // the second jump
        doubleJumped = true;
    }
}

```

Another idea would be an intuitive jump height based on how long ("hard") you press the jump key:

```
// jumpFrames is a counter to count the number of logic steps after starting the jump
if (keyDown(JUMP)) {
    if (onGround()) {
        jumpFrames = 0;
        dy = 5;
    }
    else if (jumpFrames++ < 5) {
        dY += 1;
    }
}

```

Both snippets are untested, but should work:

* The first one allows you to jump and then jump again while you're still ascending.
* The second one allows you to jump higher if you hold down the button for longer.

Both snippets assume there's some kind of friction/gravity slowing your velocity down again. The actual values might depend on your physics model.
> 2 votes

# Answer
It's hard to say with one image lacking, but maybe something like setting a target height? Like, if you hit the jump button while on the ground, target height is set to h, and if you hit it while already jumping, target height is set to 2h.
> 1 votes

---
Tags: android, box2d, andengine
---


# Question
Title: How do I check on non-transparent pixels in a bitmapdata?
I'm still working on my window cleaning game from one of my previous questions

I marked a contribution as my answer, but after all this time I can't get it to work and I have to many questions about this so I decided to ask some more about it. As a sequel on my mentioned previous question, my question to you is:

How can I check whether or not a bitmapData contains non transparent pixels? Subquestion: Is this possible when the masked image is a movieclip? Shouldn't I use graphics instead?

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

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

**Code**

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

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

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

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

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

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

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

}

```

# Answer
You're not working with bitmaps here. The `graphics` object you're using uses vector graphics. So basically you're painting a lot of rectangles to your mask...

The only reasonable way to determine whether or not your mask is entirely filled would be to render it to a `BitmapData` (using `BitmapData.draw`) and then iterate through the pixels until you hit a transparent one. In that case your mask still contains transparent parts. If you checked all pixels without hitting a transparent pixel, your mask is completely filled.

This seems overly complicated though. I'd work on a Bitmap right from the start (eg. your "dirty" layer is a bitmap on top of your clean MovieClip. Then you actually erase the dirty pixels instead of using a mask.

**Update:** I did a quick test of the Bitmap based approach. Here's the result (there's an indicator circle that always jumps to the first non-transparent pixel. Otherwise it would be too difficult to find all the pixels). And here's the source-code.
> 4 votes

---
Tags: flash, actionscript-3, pixel, masking
---


title: Cry Engine 3 vs UDK

text:
# Question
Title: Cry Engine 3 vs UDK
Me and a bunch of guys from my University are thinking about getting started in game development, but, even though the game design is kind of ready, we are stucked at the point "which Engine should we choose".

At first, we were thinking about Unity3D Free, in particular because we are pretty familiar with C# and, even better, it's completely free, but on the other hand there are some cons like no dynamic shadowing that make the realization of our game kinda hard.

So, we are thinking about moving either to UDK or Cry Engine, since they are not as expensive as Unity3D Pro (at least before the game deployment) .

The thing we are worried the most, though, is that we are kind of scared about the support for team work(i mean, that we might find it hard to coordinate our efforts without software support), since in Unity3D the team features are part of purchasable content, and we are not interested in paying that much for a project we are not even sure we can complete.

So, finally, I hope one of you knows the mentioned engines enough to give us a tip telling which one offers better team features and is advisable for guys that have barely worked before on videogames but have good object oriented programming skills.

Our game is an exploration game.

# Answer
While the feature is poorly documented, UDK has the option to integrate with Subversion, so your team can keep assets synchronised.

See this tutorial for more information: http://www.stubbornhorse.com/?p=135

Cry Engine SDK is lacking this, or any equivalent feature, as far as I can tell.

Furthermore, from having played with the two (several years with UDK, a few months with Cry), the documentation for both is less than stellar, but Cry Engine's is absolutely woeful.

If you're on any kind of time restraint, UDK get my thorough recommendation as the easier of the two to learn.
> 1 votes

# Answer
From a team-support standpoint: Definitely UDK, since it integrates with Perforce (if that's really that important to you)

As far as eyecandy goes: CryEngine 3. No questions asked. It allows for vast, lush terrains based on marching cubes and therefore not only looks really nice but is probably the best tool for outdoor levels.

From a purely technological standpoint: id tech 4 (CDK). It comes with full source access, so it's easy to modify (if you have a talented programmer well versed in C++, that is) and the CDK (more commonly known as the Dreaded Engine) even comes with a ptex based virtual texturing approach as well as Autodesk Beast (a pretty awesome lightmapping tool)

Disclaimer: Unity3D and UDK are, by far, the easiest and most thoroughly documented of the bunch. What they lack in flexibility they make up for in efficiency. With Unity3D you can easily develop a prototype in just a few days.
> 1 votes

# Answer
Make a big list of pros and cons of every engine. Rate the pros and cons. pick the one with the most score.

"no dynamic shadowing that make the realization of our game kinda hard."
\- This is probably something that you can implement yourself, cant see no engine get public without having an solution to this.
> -1 votes

---
Tags: unity, udk
---


title: Add delay between player jumps

text:
# Question
Title: Add delay between player jumps
I'm developing a platformer game and have implemented jumping for the player. The player is able to jump, but holding the up arrow causes the player to continuously jump. What would be the best way to add a small delay between jumps so that once the player lands on the ground; there is a small delay before the next jump is initiated.

# Answer
Adding an artificial delay is a really bad idea IMHO.

1) It's unexpected - what other well-known platformer does it that way?

2) It limits your player's jumping accuracy, because in tight situations, it might prove fatal (the character falls off a platform because you can't take off quickly enough), which would be the ultimate turn-off for any player - losing against the interface

3) To compensate for 2), you would have to tone down the maximum difficulty of your jumping areas. That limits how challenging and interesting you can make your game.

4) It still doesn't actually solve the problem of spamming - if you just keep holding jump, then the character will jump after the delay, like a robot. Is that really any better than jumping like a robot without delay?

There is, however, an organic solution to the problem: You just have to remember that human coordination is limited by nature. The only way for me to spam jumping is by holding the jump button. If I can't just spam the jump key, then I have to wait until my character has landed before pressing jump again. That poses a natural limit on how fast I can jump, and an artificial delay becomes completely unnecessary.

All you have to do is to check for 3 things before jumping:

* Is the state of the jump key currently "pressed"?
* Is the character on the ground?
* **In the previous frame, was the state of the jump key "not pressed"?** (you have to save the previous key state of course)

If all checks are true, then the character jumps.

The great upside to this method is that I can actually improve my jump frequency by training, and really, that's what the vast majority of players want from their games: Getting better at it. With an artificial limit, you set a hard limit on how good I can become at jumping in your game, and if I feel I could do better but you don't let me, I will be disappointed and stop playing quickly.
> 5 votes

# Answer
Or you can simply use instead of `input.isKeyDown(Input.YOURKEYHERE)` use `input.isKeyPressed(Input.YOURKEYHERE)`. With that you will go to the if statement only once per button and the player will jump only once.
> 1 votes

# Answer
You can add a little timer:

```
public void jump() {
   if(gameTime.getTimeMS() - jumpTime > jumpDelayInMilliseconds) {
       jumpTime = gameTime.getTimeMS();
       character.jump();
   }

```

Basically you are noting the last time your character jumped, then ensuring that enough time has passed before issuing the jump command again.

Note that the code above is not specific to Slick2D, just javaish pseudo code.
> 0 votes

# Answer
I don't think you want a time delay between jumps; what you want is to only jump once when a button is pressed. That is, don't jump over and over while the button is held down, require a new button press each time.
> 0 votes

# Answer
You can use this little trick :

```
if(Jump == true){

        if(JumpFall == false){
            shiftY -= 1;
        }
        if(shiftY == PUT_YOUR_JUMP_HEIGHT_HERE){
            JumpFall = true;
        }
        if(JumpFall == true){
            shiftY += 1;
        }
        if(shiftY >=PUT_YOUR_STARTING_HEIGHT_HERE){
            Jump = false;
            JumpFall = false;
        }
    }

```

So , Jump is a boolean variable telling that now you are jumping , shiftY is an int variable for player's height and JumpFall is a boolean variable telling that you have to fall now ,the jump is over .So, adding this part of code into your game loop (update loop in Slick2D) and setting Jump to True when you press the Up Key for example will make your character jump from your starting height (for instance, the ground) and jump up to your jump height (for example till reaching a bonus box) and then you will see your player going down to the ground like super mario does. The Last if() just Initializes the whole group.
> 0 votes

---
Tags: java, slick
---


title: Unity3D or UDK or OPENGL from scratch?

text:
# Question
Title: Unity3D or UDK or OPENGL from scratch?
I am just very confused which I should choose in terms of high end game development. The application that I am designing is pretty simple, requires some 3D, and some effects. I am looking at a game similar to ping pong, but with high textures and graphics. I will just need web services to submit high scores.

From my description, you can see that its pretty straight forward and I am confused whether I should use **Unity3D** or **UDK** or write the entire application myself with **openGL** (which will take a lot of time though).

If you had faced this dilemma before, and chose for a particular graphics engine, please provide your suggestions and reasons as to why that was better. It would be helpful.

Also, how can this affect in terms of *investment* and *revenue* ?

# Answer
This topic appears very regularly here. I'd suggest reading through the many other iterations to get further answers.

In my opinion, UDK is good for making first person shooters and little else. The online documentation isn't much beyond automatically created documentation from the source files (what comes out of things like Doxygen). I'm working on a student project in UDK that is a third person platformer. It's been unnecessarily difficult at times.

Unity is pretty fast to learn, well-documented, and capable of a variety of game types. Its versatility can make some tasks trickier than others, however, but the Unity community can be pretty helpful in finding answers to your questions. I think it's a good choice for simple or quick projects.

Writing it on your own in OpenGL could be a great learning or practicing experience if that's what you want. Not knowing your skillset, though, makes it hard to know whether it's worth it. If you want something done quickly, doing it on your own may not be the best decision. If you want to learn a lot about the process (engine, game, 3D programming, etc.), it may be a good idea.
> 5 votes

# Answer
In case of such a simple game design idea, I'd use Unity3D if I were you.

Alternatively, it might be worth checking out Panda3D or a game development focused programming language such as Blitz3D or Dark Basic Pro. All of them are pretty good in terms of flexibility, performance and development speed.
> 1 votes

# Answer
For every project the same rule applies: "Good, Cheap, Fast. Pick any two."

I found a good management tool. Draw a circle. Write the three options evenly spaced on the edge. Determine where on the edge of the circle you want your project to fall. Draw a line from the center to your spot. (Those plastic signs with clock hands attached that are captioned "We're closed! Be back at", work fine). Pin it up on the wall and look at it when you're making decisions.

You can be good and cheap but expect to spend years doing everything yourself from scratch. You can be fast and cheap but don't expect to win any awards. etc.
> 0 votes

---
Tags: opengl, iphone, unity, udk
---


# Question
Title: GPU optimization question: pre-computed or procedural?
I'm learning shader program and need some general direction.

I want to add noise to my laser beam.

Which is the best way to handle it?

I could pre-compute an image and pass it to the shader. I could then use the image to change the opacity and easily animate the smoke by changing the offset of the texture lookup.

I could also generate noise in the shader and do the same thing the texture was used for.

Is it generally better to avoid I/O to the graphics card or the opposite?

# Answer
I'd go with the first approach. It's not only easier to pull of but also more elegant. While this kind of overhead on the GPU mustn't necessarily be avoided (it's not fatal to go with your second approach), I'd rather save it up for something more worthwhile.

Now if the question was about whether to use a high-poly mesh or tessellate/displace a low-poly one in realtime, I'd definitely say go for the later. Such would be a case in which utilizing a shader rather than a pre-baked asset would be most advisable, as you'd otherwise waste a lot of good bandwidth.
> 1 votes

# Answer
depending if you are fillrate bound or memory bound, you can chose from that. but other than that, but i would go with the texture. that way you can let artist control the noise aswell.
> 1 votes

---
Tags: shaders, optimization
---


title: Difference between libgdx and andengine

text:
# Question
Title: Difference between libgdx and andengine
How to choose between libgdx and andengine?. Some people suggest using ligdx. Some others prefer andengine. If someone is favouring one above the other what would he consider choosing betweeen the two?

# Answer
> 6 votes
It's a matter of preference.

On the one hand, Andengine is a lot more beginner friendly. On the other, libgdx is quite powerful and offers bindings for OpenGL 1.0, 1.1 and 2.0.

libgdx, while being really lightweight compared to Andengine, is also capable of delivering a fully 3D experience while Andengine caters for developers and game designers interested in it's 2D capabilities.

See here for a more thorough comparison:

http://www.dustypixels.com/2010/11/17/native-android-ogl-game-libraries-3-of-the-best/

---
Tags: android
---


# Question
Title: State / Screen management in Entity Component Systems
My entity/component system is happily humming along and, despite some performance concerns I initially had, everything is working fine.

However, I've realized that I missed a crucial point when starting this thing: how do you handle different screens?

At the moment, I have a GameManager class which owns a component manager and entity manager. When I create an entity, the entity manager assigns it an ID and makes sure it's tracked.

When I modify the components that are assigned to an entity. an `UpdateEntity` method is called, which alerts each of the systems that they may need to add or remove the entity from their respective entity lists.

A problem with this is that the collection of entities operated on by each system is determined solely by the individual Systems, typically based on a "required component" filter. (An entity has to have a `Renderable` component to be rendered, for instance.)

In this situation, I can't just keep collections of entities per screen and only Update/Draw those collections. They'd have to either be added and removed depending on their applicability to the current screen, which would cause their associated components to be removed, or enable/disable entities in a group per screen to hide what's not supposed to be visible.

These approaches seem like really, really crappy kludges.

What's a good way to handle this? A pretty straightforward way that comes to mind is to create a separate `GameManager` (which in my implementation owns all of the systems, entities, etc.) per screen, which means that everything outside of the device context would be duplicated. That's bothersome because some things are always visible, or I might want to continue to display the game under a translucent menu window.

Another option would be to add a "layer" key to the `GameManager` class, which could be checked against a displayable layer stack held by the game manager. `*System.Draw()` would be called for each active layer, in the required order as determined by the stack. When the systems request an iterator for their respective entity collections, it would be pre-filtered to a (cached) set of those entities that participate in the active layer. Those collections could be updated from the same `UpdateEntity` event that's already used to maintain each system's entity collections.

Still, kinda feels like a hack. If I've coded myself into a corner, feel free to throw tomatoes as long as they're labeled with a helpful suggestion.

Hooray for learning curves.

# Answer
> 4 votes
After trying a few different approaches, I implemented the following, and it's working quite well.

Briefly:

I have a `GameManager` class which is responsible for maintaining systems, components and resources.

```
public class GameManager : Disposable
{
    public EntityManager EntityManager { get; private set; }
}

```

`GameManager` is the game's primary interface to the engine. It provides methods for creating entities, etc. The relevant part here is `EntityManager` (abbreviated, relevant methods shown):

```
public class EntityManager
{
    public List<IEntity> Entities { get; private set; }
    internal Dictionary<string, EntityCache> Caches { get; private set; }

    private Channel _nextChannel = null;

    internal EntityCache CreateCache(string name, params Type[] filter)
    {
        name = name.Trim().ToLower();

        if (Caches.ContainsKey(name))
            throw new Exception("A cache of the same name already exists");

        var cache = new EntityCache();
        cache.Filter = filter;

        Caches.Add(name, cache);

        return cache;
    }

    private bool MatchesFilter(IEntity entity, IEnumerable<Type> filter)
    {
        return filter.All(t => entity.Is(t));
    }

    internal void PreUpdate(float dt)
    {
        if (_nextChannel != null)
        {
            foreach (var kv in Caches)
            {

                var cache = kv.Value;

                cache.ActiveItems.Clear();
                cache.ActiveItems.AddRange(
                    cache.Items.Where(
                        (entity) =>
                        {
                            var enable = !entity.Is<Channel>() || entity.As<Channel>() == _nextChannel;
                            entity.Enabled = enable;
                            return enable;
                        }
                )
                );
            }
            _nextChannel = null;
        }

    }
    /// <summary>
    /// update the caches by adding or removing the specified entity, based on its assigned components
    /// </summary>
    /// <param name="entity"></param>
    internal void Update(IEntity entity)
    {
        if (!Entities.Contains(entity))
            Entities.Add(entity);

        if (Manager.Components.ContainsKey(entity))
        {
            var components = Manager.Components[entity];

            foreach (var cache in Caches.Values)
            {
                var matches = MatchesFilter(entity, cache.Filter);
                var contains = cache.Items.Contains(entity);

                var active = entity.Is<Channel>() ? (entity.As<Channel>() == _nextChannel) : true;

                if (matches && !contains)
                {
                    cache.Items.Add(entity);
                    if (active)
                        cache.ActiveItems.Add(entity);

                }
                else if (!matches && contains)
                {
                    cache.Items.Remove(entity);
                }

            }
        }
    }

    public void SetChannel(Channel channel)
    {
        _nextChannel = channel;
    }

}

```

`EntityManager` maintains filtered caches of entities:

```
internal class EntityCache
{
    /// <summary>
    /// list of component types that this filter requires
    /// </summary>
    public Type[] Filter { get; internal set; }

    /// <summary>
    /// all items in the system that match this filter (set by EntityManager)
    /// </summary>
    public List<IEntity> Items { get; private set; }

    /// <summary>
    /// Items that are active (should be updated, drawn, etc.)
    /// </summary>
    public List<IEntity> ActiveItems { get; private set; }

    internal EntityCache()
    {
        Items = new List<IEntity>();
        ActiveItems = new List<IEntity>();
    }
}

```

Also, a `Channel` component is used to group entities into groups/channels/screens. (`Channel` exposes a `ChannelId` property used to separate groups.)

When `EntityManager` starts its `Update` cycle, it checks if a channel change request has been received. If so, it rebuilds the `ActiveItems` lists. Entities that have a `Channel` component attached are added to the ActiveItems collection if their channel is the same as the next selected channel. Entities that do not have a `Channel` component are always active (good for global input processors, debug displays, loggers, etc.)

Systems only operate on the `ActiveItems` collections during the Draw and Update cycles.

So, when initializing a game, I might do this:

```
var playChannel = new Channel("play");
var menuChannel = new Channel("menu");

var ship = GameManager.Create("ship");
...add ship rendering components...
ship.Add(playChannel);

var splashLogo = GameContent.Create("splash-screen-logo");
...add logo rendering components...
splashLogo.Add(menuChannel);

Manager.EntityManager.SetChannel("menu");

```

The last line updates the `ActiveItems` collections, so on the next cycle, any entities with an attached Channel with ID "menu" will be drawn and updated, but everything else will be ignored. An input processor switches channels when required.

I also added a small serialization-friendly state machine which handles navigation between screens, but that's another topic.

I initially had each System maintain its own entity caches, but I found myself creating systems which required the same component filters, so those caches would be duplicated. Moving them into an EntityManager provided a centralized interface to all of the entities in the game, made implementation of the screen/channel system fairly trivial, and made it much easier to remove entities and components from the game when necessary.

Hope this helps someone!

---
Tags: entity-system, screen-management
---


# Question
Title: XNA 4.0: Problem with loading XML content files
I'm new to XNA so hopefully my question isn't too silly. I'm trying to load content data from XML.

My XML file is placed in my Content project (the new XNA 4 thing), called "Event1.xml":

```
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
  <Asset Type="MyNamespace.Event">  // error on this line
    <name>1</name>
  </Asset>
</XnaContent>

```

My "Event" class is placed in my main project:

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

namespace MyNamespace
{
    public class Event
    {
        public string name;
    }
}

```

The XML file is being called by my main game class inside the LoadContent() method:

```
Event temp = Content.Load<Event>("Event1");

```

And this is the error I'm getting:

```
There was an error while deserializing intermediate XML. Cannot find type "MyNamespace.Event"

```

I think the problem is because at the time the XML is being evaluated, the Event class has not been established because one file is in my main project while the other is in my Content project (being a XNA 4.0 project and such).

I have also tried changing the build action of the xml file from compile to content; however the program would then not be able to find the file and would give this other warning:

```
Project item 'Event1.xml' was not built with the XNA Framework Content Pipeline. Set its Build Action property to Compile to build it.

```

Any suggestions are appreciated. Thanks.

# Answer
This is a typical scenario. You must create a 3rd project and place your event class in it. Set the other 2 projects to depend on it so it builds first. Set a reference to the 3rd project in the other 2 projects.
> 6 votes

# Answer
Agree with Steve H. Just make a third project called Resources or DataTypes or something along those lines, and add the reference in your other projects to it, as Steve said. Put your Event object in that new project, and make the XML file Compile for its build action.
> 1 votes

---
Tags: xna, xna-4.0, xna-content-pipeline
---


title: Box2dWeb and Images

text:
# Question
Title: Box2dWeb and Images
How do I import and attach a PNG or GIF to a shape in Box2dWeb?

The best resource I could find online is at: http://www.jeremyhubble.com/box2d.html

However, this "tutorial" doesn't give much explanation about how images are actually used. So it is clearly possible, but I can't get the userData trick to work.

# Answer
You are generally responsible for rendering the state of your box2d world - the "userData trick" you refer to is not really to do with the box2d framework.

userData is a placeholder for arbitrary data that you want to associate to a body. This could be anything - a string, function, object, etc. This data is typically used to help you render your world during the update loop, which is exactly what the resource you linked to does - If you look at the processObjects function it uses the imgsrc value to create an Image object and draws it onto the canvas at the correct location. (This isn't really a good idea because the image is created once per object per iteration - I would suggest it should only be created once)

Here's a quick sample that shows how you can use a PNG to represent a box2d object - you'll need an 50x50px image called "image.png" and the box2web javascript file from the project site in the same folder as the html.

```
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <canvas id="canvas" width="1024" height="700" />

    <!-- Get this from the box2dweb project site -->
    <script type="text/javascript" src="Box2dWeb-2.1.a.3.min.js"></script>

    <script type="text/javascript">
    var CANVAS_WIDTH = 1024, CANVAS_HEIGHT = 700, SCALE = 30;

    var b2Vec2 = Box2D.Common.Math.b2Vec2
            , b2BodyDef = Box2D.Dynamics.b2BodyDef
            , b2Body = Box2D.Dynamics.b2Body
            , b2FixtureDef = Box2D.Dynamics.b2FixtureDef
            , b2Fixture = Box2D.Dynamics.b2Fixture
            , b2World = Box2D.Dynamics.b2World
            , b2MassData = Box2D.Collision.Shapes.b2MassData
            , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
            , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
            , b2DebugDraw = Box2D.Dynamics.b2DebugDraw;

    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");

    var world = new b2World(new b2Vec2(0, 2), true);

    // Create some objects in the world
    var fixDef = new b2FixtureDef();
    fixDef.density = 1.0;
    fixDef.friction = 0.5;
    fixDef.restitution = 1;
    var bodyDef = new b2BodyDef();

    for (var i = 0; i < 40; i++) {
        bodyDef.type = b2Body.b2_dynamicBody;
        bodyDef.position.Set((Math.random() * 400) / SCALE, (Math.random() * 400) / SCALE);
        bodyDef.linearVelocity.Set((Math.random() * 12) + 2, (Math.random() * 12) + 2);

        fixDef.shape = new b2PolygonShape();
        fixDef.shape.SetAsBox(25 / SCALE, 25 / SCALE);
        world.CreateBody(bodyDef).CreateFixture(fixDef);
    }

    // This is where you load the image data - make it a 50px x 50px image
    // You should use some sort of pre-loader to make sure the image is loaded prior to
    // using it.
    var image = new Image();
    image.src = "image.png";

    // Set up the game loop - you might want to look into using window.requestAnimationFrame
    // or some variation of that.
    window.setInterval(gameLoop, 1000 / 60);

    function gameLoop() {
        // Update the box2d world
        world.Step(1 / 60, 8, 3);
        world.ClearForces();

        context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

        for (b = world.GetBodyList() ; b; b = b.GetNext()) {
            if (b.GetType() == b2Body.b2_dynamicBody) {
                var pos = b.GetPosition();

                context.save();
                context.translate(pos.x * SCALE, pos.y * SCALE);
                context.rotate(b.GetAngle());
                context.drawImage(image, -25, -25);
                context.restore();
            }
        }
    }

    </script>
</body>
</html>

```

Hope that helps!
> 9 votes

# Answer
Maybe this can help too. Have a look. http://codingowl.com/readblog.php?blogid=134
> 1 votes

---
Tags: javascript, box2d
---


# Question
Title: XNA Deferred Shading, Replace BasicEffect
I have implemented deferred shading in my XNA 4.0 project, meaning that I need all objects to start out with the same shader "*RenderGBuffer.fx*". How can I use a custom Content Processor to:

1. Not load any textures by default (I want to manually do this)
2. Use "*RenderGBuffer.fx*" as the default shader instead of BasicEffect

Below is the progress so far

```
   public class DeferredModelProcessor : ModelProcessor
    {
       EffectMaterialContent deferredShader;

       public DeferredModelProcessor()
       {

       }

       protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
       {
           deferredShader = new EffectMaterialContent();
           deferredShader.Effect = new ExternalReference<EffectContent>("DeferredShading/RenderGBuffer.fx");

           return context.Convert<MaterialContent, MaterialContent>(deferredShader, typeof(MaterialProcessor).Name);
       }
    }

```

# Answer
> 1 votes
After a day of a lot research, this is how you do it:

```
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;

namespace Deferred_Pipeline
{
    [ContentProcessor(DisplayName = "Deferred Model - Archon")]
    public class DeferredModelProcessor : ModelProcessor
    {
        public DeferredModelProcessor()
        {

        }

        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
        {
            EffectMaterialContent deferredShader = new EffectMaterialContent();
            deferredShader.Effect = new ExternalReference<EffectContent>("../ArchonContent/DeferredShading/RenderGBuffer.fx");

            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();
            processorParameters["ColorKeyColor"] = this.ColorKeyColor;
            processorParameters["ColorKeyEnabled"] = this.ColorKeyEnabled;
            processorParameters["TextureFormat"] = this.TextureFormat;
            processorParameters["GenerateMipmaps"] = this.GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] = this.ResizeTexturesToPowerOfTwo;

            return context.Convert<MaterialContent, MaterialContent>(deferredShader, typeof(MaterialProcessor).Name, processorParameters);
        }
    }
}

```

---
Tags: xna, c#, xna-4.0, xna-content-pipeline, deferred-rendering
---


# Question
Title: Logic that can traverse all possible layouts, but not checking every combination of identical pieces?
Suppose we have a grid of arbitrary size, which is filled by blocks of various widths and heights. There are many 2x2 blocks (meaning they take a total of 4 cells in the grid) and many 3x3 blocks, as well as some 5x4, 4x5, 2x3, etc.

I was *hoping* I could set up a program that would look at all possible layouts, and rank them, and find the best one. Simply it would look at all possible positions of these blocks, and see what setup is the best rank. (the rank based on how many of these can be connected by a roadway system of 1x1 road blocks, and how many squares can be left empty after this is done. - wanting to fit the most blocks as possible with the least roads.)

My question, is how should I traverse all the possibilities? I could take all the blocks and try them one at a time, but since all 2x2 blocks are equal, and there are a couple dozen of them, there is no point in trying every combination there, as in the following

```
AA BBB
AA BBB
 CCBBB
 CCEEE
DD EEE
DD EEE

```

is exactly the same as

```
CC EEE
CC EEE
 AAEEE
 AABBB
DD BBB
DD BBB

```

You notice that there are 2 3x3 blocks and 3 2x2 blocks in my two examples. Based on the model I have now, the computer would try both of these combinations, as well as many others. The problem is that it is going to try every single possible variation of my couple dozen 2x2 blocks. And that is sorely inefficient.

Is there a reasonable way to take out this duplicated work, somehow getting the computer program to treat all 2x2 blocks as equal/identical, instead of one requiring rearranging/swapping of these identical blocks?

Can this be done?

My current pseudo code

```
blocks = array of all blocks [2x2, 2x2, 2x2, 3x3, 3x3]
iterate(0)
function iterate(i) {
    currentblock = blocks[i]
    for each possible position of currentblocks
        see if there are any more blocks to place, and if there are
            iterate(i+1)
        else
            all blocks are placed, so get the rank
            if the rank is better than thebestrank
                thebestrank = rank
                thebestposition = position
}
at this point, we proceed with thebestposition.

```

# Answer
> 3 votes
When you iterate over each possible position of currentblocks, instead of placing it automatically, check a 'previously placed' list, and if this current combination of blocks (including the one you're considering placing) has already been tried, skip this possible position. When comparing the combinations, treat similarly sized blocks as equivalent.

When you successfully place a block, add the current combination of block positions to the 'previously placed' list before recursing.

You are basically running a depth-first search that has multiple ways of reaching equivalent goals - so you need to keep track of previous approaches to ensure that you don't duplicate them.

# Answer
> 2 votes
Instead of telling the computer program to test each different type of 2x2 block separately, tell it to only test one of those types of 2x2 block.

**Addendum:** In your pseudocode, all you need to do to implement this is to change your first line to:
`blocks = array of all blocks [2x2, 3x3]`

# Answer
> 0 votes
Off the top of my head to place some identically sized blocks without duplicates you'll want something like this.

```
  Firstly enumerate all legal positions for a 2x2 block.

  function PlaceBlock(int blockcount, int start = 0)
  {
    if (blockcount <= 0) {OutputCurrentSetup(); return;}
    for (int i=start; i < legal_position_count; i++)
    {
      if (legal_position[i].IsBlocked()) continue;
      legal_position[i].Apply();
      PlaceBlock(i + 1, blockcount - 1);
      legal_position[i].UnApply();
    }
  }

```

# Answer
> 0 votes
Thanks for your quick answers. I did find a simple way to edit my code to prevent duplicated iterations. However, it seems my idea of checking every possible combination is impractical, due to the sheer magnitude of the total number of possible combinations, particularly when you have blocks averaging a size of 3x3 filling over 50% of the container which is 30x40

---
Tags: ai, grid
---