# Question
Title: C# Perlin noise - generating “endless” terrain chunks?
I'm currently writing a little side scroller in C#, to both learn C# and have fun. Right now I have a simple random number generator generating the world but it isn't exactly all that great - so with some research, I've discovered that Perlin Noise generation may help me out quite a bit. Problem is, I want to have an "endless" landscape made up of several chunks.

Basically my questions / concerns are:

1. Using minecraft as an example (Ignoring the 3rd dimension), how is Notch getting each chunk to connect to each other perfectly? Tunnels, caves, ore veins, mountains, flat lands, biomes, etc. are all connected to each other even though each chunk is generated separately, and sometimes at a much later date. This is key for me, I want the player to be able to walk to the right and as they are walking, generate more landscape that connects to previous landscape, including underground tunnels and cave systems.
2. Going off of #1, how would this be accomplished under the assumption that each chunk is a square, and the world is 10 squares high, and infinite squares wide? I.e. Each "chunk" is 128x128 tiles and the world is 1,280 tiles tall total. (This is so that I can make an infinitely deep map if I choose to - and also to show that all 4 sides of a chunk / square need to be able to connect and continue on what the previous square/chunk was doing).

# Answer
Find a C# implementation of Simplex Noise, it's like Perlin but better behaved and faster.

The thing about continuous noise functions like Perlin and Simplex is that they are deterministic, **noise is not random**. What most noise implementations use is a Seed value that offsets into the noise generated which makes Seed=1 different from Seed=2.

Because of the above observation you can keep reusing the Seed and all the new terrain generated as you move through the noise function will match up because it just picks up where you left off.

This part of it is pretty simple and quite nice, what you do with the generated noise is where the magic happens.

To James, that's possible but my personal speed test with a 3D noise showed simplex to be faster at 3, could be any number of factors in my personal test but it matched the general idea in literature. Even if it were slower I would recommend simplex because it doesn't show the "square" artifacts that perlin does.

To Jon, Noise is a math function and it just spits out results from parameters and given the same parameters you will get the same number back. I see where the confusion might come from.

This noise function is sampled like: number=noise(x,y,z); for 3 dimensional noise. As an example, your first map may sample from X=0.0 to X=1.9, the map just to the right of it continues and samples from X=2.0 to 3.9

Part of the art of using noise is finding good ranges to sample, deciding on how many octaves, filtering and processing etc... Take a look at a handy noise library to see a few examples and some source code of Perlin in action.
> 10 votes

# Answer
a noise table is precomputed to seamlessly tile, just like any other seamless texture map. so that's why you can go to point X and it will be the same everytime, very important in animations so textures dont change from frame to frame.

there is a thread about this on answers.unity3d.com (procedural side scroller level generation)

also, the 1994 book "procedural modeling and texturing" discusses noise and multi-fractals (layered noise with different frequencies and rotations).
> 2 votes

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


title: Feasible 4D first person gameplay

text:
# Question
Title: Feasible 4D first person gameplay
I put together a quick demo of a 4d first person environment last night in XNA. It uses 3d cross-sectioning instead of projection. (Use A and O to move in and out from 0 to 1 in the W axis.)

In my demo I made a tunnel where it's blocked off at first, but the path appears as you travel in W. I immediately noticed while trying it that it doesn't feel very interesting. It looks the same as if you were just pushing the block out of the way. Of course the block could change shape too but it doesn't help the feel much.

There are some other approaches I could try to make it more interesting:

Miegakure, from the demo videos, uses cross sectioning, but it also seems to allow you to swap one of your spatial axes for W, so you can see the movement in that direction.

I could try to do 3d projection instead of cross sectioning. For this to have any noticeable effect, I would have to also allow rotation that lets you look "around" objects in 4D, giving you something like this. I feel like this could be insanely confusing to a player, and also would make it really tough to design workable puzzles.

The last thing I could try that seems reasonable would be to keep my cross-section approach, but allow the objects to rotate in W, and implement the truncated solid calculations.

I'm looking for feedback on whether these would be usable as mechanics or if it's just way too confusing to a player, or even a level designer. What has been tried successfully, beyond simple demos? So far it looks like Miegakure is the only game that has been taken seriously.

# Answer
I've been obsessed with all things 4D since childhood, so I am pretty thrilled to see dimension-transcending games like Miegakure and Fez (and to some extent echochrome and Hazard/Antichamber, Portal, etc.) getting attention. I think, as a community, we should definitely be "pushing the dimensional boundaries" so to speak, and for being part of that forefront I applaud you sir!

But on to your question:

I've given a lot of thought to all the various perspectives/POVs used in games (both 2D and 3D) and how they might be realized analogously in 4D. For example, what would a 4D Metroidvania look like? A 4D "DooM" (1st person POV, with gravity) or "Descent" (1st-person, but no gravity, and all degrees of freedom) or "Mario Galaxy" (3rd person, with gravity)? Similarly, a side-view platformer like the original "Super Mario Bros." which has gravity, vs. a top-down view like the original "Pac-Man" where gravity is only implied and motion in all directions is free?

The strategies I've seen out there for conveying 4D objects/spaces are usually one of the following:

1. Project the 4th axis onto 3D space (there are several possible ways)
2. Show only a certain 3D slice of 4D space (Miegakure's and your approach)
3. Use stereo viewing (e.g. 3D glasses) to convey the extra 4D "hyperdepth"
4. Simulate a 4D being's "3D retina" and how it would perceive the 4D world
5. Allow us to only explore the 3D surface of a 4D geometric figure

How can we meaningfully compare these approaches, which all seem reasonable enough at first glance? One way is to appeal to lower-dimensional analogy -- hey, it's been done ever since "Flatland"! Namely, you ask yourself instead:

```
In what ways could you convey a 3D interactive world/experience to a 2D being?

```

And remember, the 2D being is "embedded" in the plane, and therefore sees everything "edge-on" -- i.e. it has merely a 1D linear camera/screen/retina that is the field of view, just as we 3D beings project our 3D world onto our 2D retinas/monitors.

(Note: let's assume the 2D being still has two eyes though, and uses stereo vision to perceive "depth" and distance in 2D, just as we do for distances in 3D.)

Now let's go again through those options listed above, as if we're talking 2D beings trying to understand 3D. In reverse order, just for the fun of it:

```
#5.  Allow a 2D player to explore the surface of a cube/cylinder/torus/whatever.

```

If you've ever played a game with "wrap-around" where you can go off one side of the screen and you end up instantly on the other side, you've already done this. Does it really convey a sense of 3D shape though? Do you get a sense of the 3D volume that is enclosed by the cube/cylinder/torus/whatever topology you are exploring? Not really...

If you were a little 2D ant exploring the surface of a cube, you'd just find that the individual "rooms" (say each face of the cube is a room) connect to each other a little bit unorthodoxly. You'd have a hard time wrapping your little ant-brain around the fact that there are "folds" between each room, if you are *embedded* in the surface of the cube and cannot actually see the folding from "above".

Here is a demo by Jason Hise that implements this idea in 4D though:

http://www.jasonhise.com/index.php?option=com\_content&view=article&id=46:tesseract-explorer&catid=34:projects&Itemid=53

And if you've seen the movie "Cube" and its sequels, you probably get the gist of it. On to the next!

```
#4.  Show a 3D being's "retina" and show how it would perceive its 3D world.

```

This is to say: take "DooM" or "Call of Duty" or some FPS and instead of a monitor, use a projector to project the screen onto the plane of this poor confused 2D being. What would they make of this bizzare image? Remember, they are embedded in the plane of the screen, they are not looking at it "from above" as we do. (In fact, they don't even know what a simple square really looks like, since all they've ever seen is its edges -- line segments.)

Suppose their eye is located at {x=0,y=0} and they are looking forwards in +x, just as Mario would be standing upright and looking towards the right. The screen is hanging in front of them, crazy things are happening on the screen, explosions, rotations and whatnot, but the basic shape of the screen is fixed -- a 1920x1200 rectangle or whatever.

First of all, since they're looking at it edge-on, you'd have to make everything semi-transparent so they could see all the content on the screen, otherwise (to them) objects at the left side of the screen will obscure objects at the right side of the screen, even though (to us) that's not what really happens.

Second of all, I don't like that the 2D person's innate sense of depth perception is not being used to its fullest capacity here. To wit, there is option #3:

```
#3.  Use stereo viewing to convey the extra 3D "depth"

```

I like this slightly better, because we can convey to the 2D being that certain things in the scene are very far away (in the 3D z-axis sense) even though they might be shown projected smack in the middle of this 1920x1200 screenshot. But it would still take some training for the 2D eye to really treat the "stereo depth" and the normal "distance along its view direction" as different types of depth.

Here is an applet that utilizes strategy #3 for 4D space:

http://www.urticator.net/maze/

Next we have:

```
#2.  Show only a certain 3D slice of 4D space (Miegakure's and your approach)

```

My least favourite option, I'm sorry! Think about lifting "Paper Mario" out of his plane of existence and sweeping him around in 3D space -- but really think about what he would see, not what you (the player) are seeing. It's gotta be super confusing for the poor little guy, as he observes only cross-sections of the world, like an MRI scan, and is supposed to make sense of these slices of objects suddenly appearing/disappearing in and out of view in various arbitrarily-angled profiles?

Also, it's a very "lossy" perspective to use, compared to the other three options, since you are completely discarding everything except one infinitesimal plane (space?) slice of the 4D world. At least with the projection-based strategies, you still get to see what's out there beyond your local 3D volume!

Which brings us finally to:

```
#1:  Project the 3rd (z) axis onto the 2D (xy) plane.

```

Like I said above, there are several ways to do this -- isometric, non-isometric, orthographic, perspective-projection, etc. etc., covered nicely here:

http://en.wikipedia.org/wiki/Graphical\_projection

What's more interesting to me is: how can you best make use of your 2D character's innate sense of depth perception?

Let's go back again to Mario standing upright and looking towards the right (+x axis). Mario has depth perception: things that recede into the distance will appear smaller and farther away to his beady little 2D eyes. It'd be nice if the 3rd axis (what we think of as "depth") were projected at least somewhat to recede into the +x distance. Not necessarily to coincide with the +x axis, but maybe lean towards it.

On the other hand, if we think of Pac-Man, the 3rd axis for him is not a new kind of "depth" but it would be a new concept called "height". How do make sense of this in 3D -to-4D?

Imagine running "DooM" on your brand new iPad 4. Now lay it down flat on the table, and behold, all the 3D space in the world of the game appears somewhat flattened and distorted from a bird's eye view. Now extrude a 4th axis out of the plane of the iPad, coming up off the table, and behold: it is perpendicular to all three "3D" axes that are embedded in the screen of the iPad. Your character in the game might even try to move towards/away from the camera in that world, but no matter what axis he moves in, he can never leave his "plane of existence" whereas your 4th axis does.

So what I'm trying to say is, instead of the 4th axis being a different kind of "depth" you could also flatten 3D space down onto the floor, and let the 4th axis be a new kind of "height". In this way, you could have a "3D floorplan" for a room, rather than merely a 2D floorplan. See the UC neuro lab link below for some drawings of this.

As this is already a ridiculous wall of text, I'm not going to get into rotations and whatnot -- do you want absolute "freelook" (e.g. mouselook) or maybe a hotkey to switch to a separate "mode" for 4D vs. 3D rotations? Do you restrict the rotations involving the 4th axis to some limited set? Gradually introduce them in a tutorial? (Some modes of rotation are very confusing!! The "inside-out" kind, where the 4th axis rotates into/out of the screen.) I will just refer you to:

```
Resources:

```

Have you looked at mushware.com's technical articles & demos? (freely available and really nicely detailed!) They were working on a space shooter, Adanaxis, which is an "FPS" in the sense of Descent/StarFox I guess, no gravity or platforming. But what's interesting is their 4D rotation mechanic which you can see in their video demo:

http://www.mushware.com/portal.php?page=4

where they switch momentarily (and smoothly!) to a fish-eye lens perspective, and "flatten" 3D space isometrically, to \[try to\] make it clearer when you rotate the 4th axis around any of the usual 3. Otherwise, as I said above, 4D rotation can be quite mindboggling when the 4D and 3D axes that comprise the plane of rotation are projected too co-linearly.

There is also the handy wikipedia list of 4D game projects, which I hope you've come across by now:

http://en.wikipedia.org/wiki/List\_of\_four-dimensional\_games

and there is the aforementioned cognitive research study done by the UC Irvine neuro lab, with their 3D-slice-of-4D-space (sigh) simulator:

http://cnslab.ss.uci.edu/fourdim/index.html

but one of those guys wrote a whole 4D level editor! Can we hire that guy or what?
> 5 votes

# Answer
While I agree with DeadMG that this is likely to simply overload most people's cognitive abilities, I think for the game to be particularly interesting you're going to have to allow arbitrary rotations and do the calculations there - the shapes are just that much more interesting than those that you'll get by simply extruding in the W direction.

That said, if you don't allow players to move off-axis (and to rotate their environment arbitrarily), then you'll almost certainly run into the same issue; people will simply parse it as something akin to space+time, and your W axis will be forever mentally separated from the others. It's not clear whether this is avoidable or not, but for the 4d to really be meaningful it seems like the one mental structure you're going to have to try and break.
> 1 votes

# Answer
There are no known feasible approaches, and none have been done successfully before. It's worth mentioning that it's the rare game which even takes place in free 3D space- most ultimately take place in 2 dimensions. The human brain simply isn't designed to process four dimensions, and a 2D screen can barely handle displaying 3D data.
> 0 votes

---
Tags: xna, game-mechanics, puzzle, 4d
---


# Question
Title: what is the difference between CCSprite and a PhysicsSprite?
I am new to Cocos2D and I've realized that most of the codes written before the Cocos2d update used CCSprites. Recently I realized a lot of more recent codes after the update are using PhysicsSprite. What is the difference? What advantages does one have over the other, if any?

# Answer
> 2 votes
PhysicsSprite is a CCSprite which uses a physics body to control the sprite's motion (position) and rotation.

Depending on whether you start with the Box2D or Chipmunk template, PhysicsSprite will either have a b2Body (Box2D) or a cpBody/cpShape (Chipmunk) as instance variables.

If you're not planning to use physics, use CCSprite. If you do, use PhysicsSprite for those sprites which represent physics objects.

---
Tags: physics, cocos2d-iphone, cocos2d
---


title: Moving a sprite accelerometer

text:
# Question
Title: Moving a sprite accelerometer
Im trying to, in cocos2d for the iPhone, move a CCSprite (in this case "player" up and down (the app is in landscape). How can I accomplish this? I have been unable to do so. ex.

```
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    player.position.x = acceleration.x * 10;
    NSLog(@"Accelerometer x value is %f\n", acceleration.x);
}

```

# Answer
> 1 votes
You can't change position components like `x` and `y` directly. You have to set a new position instead, by assigning a `CGPoint` to the position property. Something like this:

```
[player setPosition:ccp( acceleration.x * 10, player.position.y )];

```

If you want to move the sprite constantly in the direcion of acceleration, you should increment the `x` value instead.. something like this:

```
[player setPosition:
    ccp( player.position.x + acceleration.x * 10, player.position.y )];

```

Technical background: You have to use `setPosition` or `position = ccp(xValue, yValue)`, because Cocos2D keeps a flag internally that indicates if the position has changed and if the sprite should be moved. Setting components like `x` or `y` directly won't do anything, because the flag only changes when you invoke the `position` setter.

---
Tags: cocos2d-iphone, hardware-acceleration
---


title: Scaling Model in XNA, keep position

text:
# Question
Title: Scaling Model in XNA, keep position
I am trying to create a little fun 3D game in XNA, but I am having some problems with scaling my models. I use models from random sites, so my battleship is for an example 10 times larger than my planet.

I thought I had found out how to scale my model, but it does not show up when I do, or the coordinates get really messed up. Is there a way to scale my models but still keep the same position system?

Here is my model base class.

```
public class BaseModel
{
    protected Matrix world = Matrix.Identity;
    protected Matrix RotationMatrix = Matrix.Identity;
    protected Model model;
    protected float scale = 1.0f;
    protected Vector3 direction;

    public Vector3 Position
    {
        get
        {
            return world.Translation;
        }
        set
        {
            world = Matrix.CreateTranslation(value);
        }
    }

    public BaseModel(Model model, Vector3 position, float scale = 1)
        : this(model, position, Vector3.Zero, Matrix.Identity, scale)
    {
    }
    public BaseModel(Model model, Vector3 position, Vector3 direction, float scale = 1)
        : this(model, position, direction, Matrix.Identity, scale)
    {
    }
    public BaseModel(Model model, Vector3 position, Vector3 direction, Matrix rotationMatrix, float scale = 1)
    {
        this.model = model;
        this.Position = position;
        this.direction = direction;
        this.RotationMatrix = rotationMatrix;
        this.scale = scale;
    }

    public virtual void Update(GameTime gameTime)
    {
        world *= Matrix.CreateTranslation(direction);
    }

    public virtual void Draw(GameTime gameTime, Camera camera)
    {
        Matrix[] modelTransforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(modelTransforms);
        Matrix wworld = GetWorld();

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = modelTransforms[mesh.ParentBone.Index] * wworld;
                effect.View = camera.view;
                effect.Projection = camera.projection;
            }
            mesh.Draw();
        }
    }

    public virtual Matrix GetWorld()
    {
        return RotationMatrix * world * Matrix.CreateScale(scale);
    }

    public virtual Model GetModel()
    {
        return model;
    }

    public virtual bool CollidesWith(Model otherModel, Matrix otherWorld)
    {
        // Loop through each ModelMesh in both objects and compare
        // all bounding spheres for collisions
        foreach (ModelMesh myModelMeshes in model.Meshes)
        {
            foreach (ModelMesh hisModelMeshes in otherModel.Meshes)
            {
                if (myModelMeshes.BoundingSphere.Transform(
                    GetWorld()).Intersects(
                    hisModelMeshes.BoundingSphere.Transform(otherWorld)))
                    return true;
            }
        }
        return false;
    }
}

```

# Answer
> 2 votes
Swap the order of multiplication in the `GetWorld` method so that the scale comes first:

```
public virtual Matrix GetWorld()
{
    return Matrix.CreateScale(scale) * RotationMatrix * world;
}

```

# Answer
> 0 votes
Try Scale * rotate * translate

```
public virtual Matrix GetWorld()
{
    return Matrix.CreateScale(scale) * RotationMatrix * world;
}

```

when scale is after translate, it scales the translation values. Think SRT when building a final matrix.

---
Tags: xna, 3d, matrix, 3d-meshes, transformation
---


# Question
Title: XNA significant loss in fps by just adding a few hundred thousand more triangles?
I've got a minecraftish game that's running nice and smooth with a total of 9.3 million triangles, about 50-70fps average. Then if I try to render 9.9 million triangles I get hell and it drops to \< 1 fps. I'm drawing them exactly the same way, it's definitely the drawing as I have a vertex buffer for each chunk, then I run through them all, check if they're in sight and if they are I draw them. It works fine at high fps until I have just those few extra triangles which destroy the FPS.

Edit: Added drawing code:

First I loop through all the chunks. I check if they're visible and if they are I mark them as visible then draw them.

```
        foreach (Chunk chunk in GlobalWorld.LoadedChunks)
        {
            if (chunk == null || !chunk.DrawThis)
                continue;

            if (!player.ViewFrustrum.Intersects(chunk.Bounding))
            {
                chunk.IsInSight = false;
                continue;
            }
            chunk.IsInSight = true;

            GlobalGame.graphicsDevice.SetVertexBuffer(chunk.VertexBuffer);
            GlobalGame.graphicsDevice.Indices = chunk.IndexBuffer;

            ChunkShader.Parameters["xWorld"].SetValue(chunk.WorldMatrix);
            ChunkShader.CurrentTechnique.Passes[0].Apply();
            GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.VertexBuffer.VertexCount, 0, chunk.IndexBuffer.IndexCount / 3);
        }

```

Then after that I draw all the transparent parts of the chunk (so they don't conflict with other chunks). I already made clear if they're visible above so I just check if that bool is true.

```
        foreach (Chunk chunk in GlobalWorld.LoadedChunks)
        {
            if (chunk == null || !chunk.IsInSight || !chunk.DrawThisTransparent)
                continue;
            GlobalGame.graphicsDevice.SetVertexBuffer(chunk.TransparentVertexBuffer);
            GlobalGame.graphicsDevice.Indices = chunk.TransparentIndexBuffer;

            ChunkTransparencyShader.Parameters["xWorld"].SetValue(chunk.WorldMatrix);
            ChunkTransparencyShader.CurrentTechnique.Passes[0].Apply();
            GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.TransparentVertexBuffer.VertexCount, 0, chunk.TransparentIndexBuffer.IndexCount / 3);
        }

```

With 3721 chunks loaded it runs fine with them all being drawn at the same time. With 3844 chunks being loaded it runs fine unless you view all of them. Now that's only just over 100 more chunks yet it's dropping from 60fps to \< 1 fps.

# Answer
You may be simply running out of VRAM, causing degenerate behavior paging into/out of main RAM when rendering your scene. How many verticies/indicies are you wrangling here? What's your vertex format like? Is this on an xbox 360 or do you have a specific GPU you can point us at?

10 million triangles x (0.5-3) verts per triangle x 5 floats (pos + 1 uv) per vert x 4 bytes per float x = **100-600MB**, and that's ignoring fragmentation, indicies, and whatever else you might have loaded (textures)
> 7 votes

# Answer
Mauling Monkey's answer is very right, but to solve your problem, I'll add my response.

I guess you aren't optimizing the cube faces away...
9 300 000 triangles means 4 650 000 faces. If each cube has 6 visible faces, this is 775 000 visible cubes. That number is too high. A correct number should be something like 20 000 cubes (that is how many visible cubes I have in my CraftMania, with a viewing distance of 100 meters).

Two cubes touching each other are having each one invisible face.

```
  +-----+-----+
 /     /     /|
+-----+-----+ |
|     |     | +
|     |     |/
+-----+-----+
      ^
   (They have this face in common, which is invisible.)

```

Try to implement this and your results will improve a lot!
> 1 votes

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


# Question
Title: Splitting up duties for a card game server
I'm working on a game where players connect to a game server and to a lobby to play a card game against others.

I have a pretty good idea how to code it and such, I'm just not sure regarding a few details.

The game will have multiple lobbies, so although all lobbies run from the same exe and server, the player is bound to a specific lobby.

When the player connects to a lobby, I need to:

-Tell all the players in the lobby about it

-Send that player their list of online friends

-Send that player the list of all players online (in that lobby)

-Send that player the list of all current games and who's playing in each game (This info is all displayed in a ListBox).

Once that player is connected, I need to ensure that while they were receiving that information, if anyone else joined, or any games ended / started etc, that they dont miss any of those messages.

In a single-threaded world, I'd find this pretty simple, but I fear this would mean horrible lag or something every time someone joins. (I could be wrong though).

I'm wondering in general what would be an ideal way to tackle this problem such that it minimizes slow downs for other players. What I mean is, the whole server should not halt for 3 seconds while a user joins.

I guess with a message system it is not too bad since the server can get work done while it waits for the reply. But how robust is such a message system? Login / Authentication be on its own thread, and then it sends a message to the lobby thread which would handle any lobby related transactions. Should each game be in its own thread or should I loop through each active game and process them iteratively?

In addition, each game has a private chat between the 4 players. Each lobby has a chat that only players in the lobby and not in a game can see.

I was also wondering if I should incrementally update the lobby for players in a game or send them a full update when they finish a game.

If anyone could lead me in the right direction for any or all of these questions I would really appreciate it.

I'm coding this in C++ with a network library called ENet, but I'm not looking for any code, but maybe psudocode.

Thanks

# Answer
> 5 votes
You've got a whole lot of meandering questions there, so here's a huge meandering response :)

**Network traffic, queueing, and consistency**

A good server needs to be event-driven and asynchronous. I'll give an example.

You say "When the player connects to a lobby, I need to: -Tell all the players in the lobby about it". That's right, you totally do! And a first attempt at writing the code would simply send all the players the necessary information. This runs into obvious problems - if one player has a very slow connection, then you'll be sitting there waiting for that one player's modem to finally send the previous packet so you can send the next packet. Not ideal.

What you really want to do is queue up messages for every player, then, when the server has a little spare time, send as much of that queued data as you can. There are plenty of ways, depending on your OS, to just send "as much as possible", then keep the rest around in the buffer until the next time you need to send data out.

This introduces its own set of problems. For example, if someone starts piling up unsent data, they'll slowly get further and further behind realtime. There's not much you can do about this besides make your network protocol use fewer bytes, but at least it won't hurt the other players. Worse, a sufficiently large player buffer could cause your server to run out of RAM. Realistically, in this case, you just disconnect the player if they fall too far behind (measured in either seconds *or* bytes - measure both and have a kill threshold for each.)

Once you've done this, the problems with lost messages go away. A player logs on, you send them a "logon" message. Then you send incremental updates as people log on and off and chat. You don't need to know how much of the logon message the player has seen - all the incremental messages are queued and will also show up. The player may get a big blob of updates immediately after the logon message, sure, but that's okay! Everything will still be consistent.

**Scalability**

Note that this can all be done singlethreaded. You'll be using something like select() or epoll() in order to make it efficient. Multithreading is a horrible tangle that you may want to avoid unless you need the efficiency - consider it a dangerous speed hack. For a card game, you won't need it. (This advice may be incorrect if you have a million users.)

It *may* be reasonable to spin up multiple *servers*, however. This can be spread out among multiple physical computers or left on just one computer. If you have dualcore computers, it may be perfectly reasonable to run two servers on one computer just so you can avoid the morass of multithreading. You want to divide your servers by role, you don't want monolithic servers that do everything. A reasonable division in your case, and note *this is almost certainly enormous overkill, don't worry about it for a long time*:

* "user" servers that handle communication with the player, network buffering, and player settings and stats.
* "lobby" servers that handle your lobby chatting and manage the creation of new games.
* "game" servers that handle the details of each game.

Each of these servers will handle a *large* number of actual elements - I'm not saying you run a game server for each game, I'm saying you run a game server for each thousand games. But if you need to expand to the multiserver world - again, you almost certainly don't - keeping your servers narrow-purpose will make your life a whole lot easier.

**Protocol**

As for questions like this:

> I was also wondering if I should incrementally update the lobby for players in a game or send them a full update when they finish a game.

you've got two questions you need to answer.

First, do you intend for players to be able to see the lobby while they're playing a game? If so, you'll obviously need to incrementally update.

Second, do you expect incremental lobby update bandwidth will be excessive? If so, then you'll obviously want to wait to update.

Personally, I think this question just isn't an important one. The bandwidth is likely irrelevant. The answer really comes down to "do what is easiest to code", IMHO. But in general, you'll have to weigh server load vs. player experience.

If you've got any further questions, toss me a comment and I'll make things clearer as needed.

---
Tags: c++, game-design, networking, server
---


title: CCSprite x and y comparison

text:
# Question
Title: CCSprite x and y comparison
I have 2 CCSprites and I want to tell if their x and y are equal I tried this:

```
if(sam.position.x == tom.position.x && sam.position.y == tom.position.y){
NSLog(@"Hooray!");
}

```

Although I do not think this is the right way to do this. Could anyone help me?

Thanks.

**ALSO** The CCSprites are named sam and tom.

# Answer
That works, but might cause problems because of floats. It would be better to factor in some margin of error.. maybe half a screen-point... that would then look like this

```
if(fabsf(sam.position.x - tom.position.x) < 0.5f && fabsf(sam.position.y - tom.position.y) < 0.5f)

```

Of course you can change the "threshold/accuracy" by increasing or decreasing the `0.5f` value.
> 2 votes

---
Tags: collision-detection, ios, cocos2d-iphone, objective-c, ccsprite
---


# Question
Title: How to save an arbitrarily large image to a file in XNA?
I have built a level editor for an XNA-based Megaman clone I am working on and one of the features I would like to implement is the ability to save a full-resolution map of the entire level (like this one). My problem is that the levels can be arbitrarily large and XNA has a texture size limit of 4028x4028. I don't need to use the texture for anything in the editor itself, only to save it to disk.

I have stored the image data in an array using game.GraphicsDevice.GetBackBufferData, but I am having trouble finding a way to store this to disk in a readable format (preferably PNG). Everything I've found online says to use the Texture2D.SetData and Texture2D.SaveAsPng methods, but those calls are restricted to the 4028x4028 max texture size.

Any suggestions?

Note: I do realize that the example map I linked above was likely created by hand and while I could certainly output multiple full-resolution images of each screen and put them together by hand in Photoshop, I would like the process to be available directly in the editor if possible.

# Answer
As far as I know there's no way around `Texture2D` size limit, so my suggestion is the following:

1. Add a reference to `System.Drawing` to your project.
2. Create an instance of `System.Drawing.Bitmap` to store your map. I don't think there's a size limit using `Bitmap`, because I even tried with sizes over 15000 pixels wide and it worked.
3. Write your data to the `Bitmap`. The easy but slow way is to use `Bitmap.SetPixel`. The harder but significantly faster way is to use `Bitmap.LockBits` (documentation). You'll also need to convert your colors from `Microsoft.Xna.Framework.Color` to `System.Drawing.Color` but that is easy with `System.Drawing.Color.FromArgb`.
4. Save `Bitmap` as a PNG to file by calling `Save` with `ImageFormat.Png` as the second parameter.

Example using the slow method:

```
bitmap = new Bitmap(width, height);
for (int x = 0; x != width; ++x)
    for (int y = 0; y != height; ++y)
       bitmap.SetPixel(x, y, System.Drawing.Color.Red);
bitmap.Save("level.png", ImageFormat.Png);

```

But I warn you that it will perform extremely slow, so use it only as a test drive, and then switch over to the `LockBits` method.
> 2 votes

---
Tags: xna, textures, maps
---


# Question
Title: XNA: int as Vector2 so i can move sprite
I am really new XNA programming, and i am having a big problem. I have a Vector2, spritePosistion, that controls what position the sprite is at, now i want to move it by 1, every time that a player hits the w button, it is having a problem 1 being and int and spritePosistion being a Vector2. So am i doing it wrong or is there a way of getting these things to work together. Here is the code

```
if (Keyboard.GetState().IsKeyDown(Keys.W))
{
    // This is the problem
    spritePosition += 1;
}

```

# Answer
It depends, you're being awfully vague in your question. For instance, in which direction do you want to move? A few examples...

* Right `spritePosition.X += 1`
* Left `spritePosition.X -= 1`
* Down `spritePosition.Y += 1`
* Up `spritePosition.Y -= 1`
> 3 votes

# Answer
You said you want to "move the sprite by one" - but in which direction? Try

```
spritePosition.X += 1;

```

or

```
spritePosition.Y += 1;

```

for X or Y movement.
> 2 votes

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


title: Player Ranking System

text:
# Question
Title: Player Ranking System
Already posted this on another forum but I'll repost it here because I'm curious if this is a good forum for game-design questions.

I'm looking to design a player ranking system for my game. The game is similar to a racing game where you get a score for individual tracks you play (based only on your own performance). Beside the score for tracks played I want a player rank. The purpose of this player rank is to:

* Make you feel like you are progressing and getting better
* Encourage you to play more
* Encourage you to play better and improve your skill
* Be enjoyable

Another way to state it is that I want to encourage playing more levels (increasing amount of play) as well as improving skill (getting higher score). It's not necessary for the rank to actually reflect your skill. Although, I suspect some amount of accuracy is needed for the score to feel meaningful.

The only ranking system I'm familiar with is the ELO-type ranking system which I feel is lacking in some ways. Although it accurately reflect the skill of the player it has the problem of not being enjoyable in my experience - it punishes bad plays, gives no rewards for trying/experimenting with new plays. It also puts a lot of pressure on you to perform well in every game which discourages casual play.

Any ideas?

Thanks

# Answer
One way is to just treat this as a basic scoring system, and do something like this:

* 10 points for playing a level
* up to 90 extra points for scoring highly on the level

This means that good players will increase their score more rapidly, but all players will see score increases over time. If you want to ensure that people can't rack up a high score and then never play again, discard any points earned more than 1 week/month/year ago, so that the leaderboard reflects the best scores of the current time period.

A system that includes rewards for playing as well trying to measure your actual skill can never be a true reflection of skill as people can 'level up' just by playing no matter how bad they are, and therefore it will never be an accurate representation of player rankings (except accidentally). But as long as the reward for winning is significantly higher than the reward for playing, it should be a decent enough approximation.

You might also consider keeping an ELO-style system for rankings but giving players other incentives to keep playing, such as a separate scoring system. This will keep your rankings fairly 'pure' but hopefully discourage people from avoiding playing to protect their ranking.

You can also do what the various boxing organisations do, and force a player to compete from time to time to stay as the 'champion' - if they don't compete, they are removed from the leaderboard until they do.
> 1 votes

# Answer
Offer both ranked and unranked play. Ranked play affects ELO, unranked does not.
> 2 votes

# Answer
The absolute system doesn't matter as much as the relative rankings. People like to see themselves advance relative to the other players. You also should consider that players will game the system to artificially inflate their rankings, and try to make that harder.

No matter what you do, players will complain that the system isn't fair; so don't be alarmed.
> 2 votes

---
Tags: game-design, leaderboards, ranking
---


# Question
Title: OpenAL seems to ignore sound attentuation/orientation for long sounds
I don't know how else to describe it in the title, sorry.

My sound engine currently works perfectly with listener positioning and sound positioning to create the attentuation and panning effects. At least, for short sounds.

I converted an .mp3 to .wav to test out playing a song from a specific point, but suddenly OpenAL ignores that the sound and the listener are not at the same place and just plays the song at full volume right in the center.

Has anyone ever had this problem before? If so, just *what* is the problem?

EDIT: If it helps, the song is stereo and the sounds are mono, all at 16 bits per sample.

# Answer
> 3 votes
WAV can also be stereo and positioning gets ignored in that case; you'll need to flatten that to mono and then everything should work like you want.

---
Tags: c#, opentk, openal
---


title: XNA - Drawing zoomed 2D sprites

text:
# Question
Title: XNA - Drawing zoomed 2D sprites
I have a tile based game. Each tile texture is loaded and then I draw each one next to the other, forming a continuous background. I actually followed this tutorial for the xml files.

http://www.xnadevelopment.com/tutorials/looksleveltome/looksleveltome.shtml

The sources of the textures are 50x50.

However, it works only it the scale is 1 (or lower), if the scale is greater

The results:

Larger size (Zoomed or 100 pixel in xml file)

We can see there are lines between the tiles, which are not in the texture. It's actually not so bad here, but in my game tileset, that's what it does:

The same effect is present whether I increase the tile size in the xml file, change the scale when drawing or use my camera to zoom.

```
//zoom code
public Matrix GetTransformation()
{
    return
       Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
       Matrix.CreateRotationZ(Rotation) *
       Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
       Matrix.CreateTranslation(new Vector3(_device.Viewport.Width * 0.5f, _device.Viewport.Height * 0.5f, 0));
}

//draw
_spriteBatch.Begin(SpriteSortMode.Immediate,
  BlendState.AlphaBlend, null, null, null, null,
  _camera.GetTransformation());

//for each tile
theSpriteBatch.Draw(mSpriteTexture, Position, Source,
  Color.Lerp(Color.White, Color.Transparent, mAlphaValue),
  mRotation, new Vector2(mSource.Width / 2, mSource.Height / 2),
  Scale, SpriteEffects.None, mDepth);

```

Is there a reason for this? A way to fix it to have a continuous texture when zoomed?

# Answer
Use `SamplerState.PointClamp` to avoid the GPU interpolating texture coordinates with the nearest points.
> 3 votes

---
Tags: xna, textures, sprites
---


# Question
Title: Game states affecting each other's objects
If I had given this question any other title it would have immediately looked like a dupe of this one. Although that has some nice ideas none of the answers actually address what I need.

I'm refactoring my game state system a bit. I already have a stack system, not to share data, but so you can leave a pause menu and return to gameplay as it was. There is also a transition type that clears the stack completely, so you can go from the title, to a menu, to in game, and those aren't stacked on each other.

I have three big state types (handlers) right now: gameplay, menus, and cutscenes. The latter two have a lot in common so they share a base class. I'm stuck right now because of how they handle entities (gameplay objects), which all three can use.

Many games have cutscenes that don't leave gameplay, they just take control and start puppeteering the characters currently on the screen. My handlers currently have their entities separate from each other, and there's no data sharing. The only affect they can have on each other is deciding whether the previous one should keep updating / drawing or not. I need to refactor things so that I can support that kind of cutscene when it's pushed on top of the gameplay state.

**How should I organize my states so that they can share entities?** I'm considering splitting my handlers in half, one side to hold objects, the other for logic to manipulate those. Then I could mix and match them, or just swap one logic for another without changing out the data. Will this work? Maybe another approach is better.

Again, I know this sounds a lot like the other question but those answers were either things I'm already doing or didn't match my situation.

# Answer
> 2 votes
To be honest, I'd consider a "cutscene" to be mostly an AI routine, not a game state. When the cutscene starts, you push a *very thin* gamestate on top that does little more than add a visual effect you want (letterboxing is traditional) and prevent the player's controls from going through. Then you just override the AI of the entities and start dancing them around as needed. I'd leave all the entities owned by the gameplay state itself - the cutscene really isn't taking over ownership, and complex ownership semantics are begging for subtle bugs.

# Answer
> 1 votes
Would it not be possible to establish a communication system between your handlers, where one handler can query for another handlers entity? Be sure to keep it as simple as possible so it does not turn into an over-complicated-mess. You could have handlers query for entity types(if any) or Ids or move entities around between handlers? But on another note: When you say "states" I assume, that one state transitions to another? I.e. there are never two different states at the same time? Couldn't you make some kind of hand-over? i.e. During state-transition one state hands over all entities under it's control to the next state.

---
Tags: architecture, state
---


# Question
Title: How can I make my program get a username?
I am making a program that I want to load music from library/music on any computer. To do this I use `Music.FromUri()`. However, I need the username from the current computer in order for the filepath to work.

Is there any way to get the username and use it in the filepath?

# Answer
You can get the current username with:

```
Environment.UsernName

```

But if you were going to use it to construct a path to the Music folder, there's an easier way:

```
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic)

```

Here's a list of all the folders you can get this way.
> 7 votes

# Answer
You used the XNA tag, so this should give you what you want: `Environment.UserName`. Here's the doc.
> 0 votes

---
Tags: xna, music
---


# Question
Title: How can I make my program load music from files?
I'm working with a XNA game and I want my program to load music files from libary/music so I can play that music in the game. It would be great if the mediaplayer class could play a playlist of all the music in library/music.

# Answer
> 3 votes
Generally, in order to play an MP3 in XNA it has to go through the Content Pipeline. If you want to learn how to do it, a quick search turned up this tutorial.

Now, to your question:

### Single Song

To play an MP3, you need to pass an instance of a `Song` to `MediaPlayer.Play`. As I stated above, you usually get the instance of your song via the Content Pipeline, but I do see it has a FromUri method.

I have never used it before, and it *may* only work for the Silverlight framework on Windows Phone, but you can give it a try.If I had to guess, I would assume it would work like this. Keep in mind that the file will have to exist. If it doesn't you will get an error. If you are distributing this game, Use the Content Pipeline. It is much better.

```
Song song = Song.FromUri(new Uri("file:///C:/Users/Joe/Music/FinalCountdown.mp3"));
MediaPlayer.Play(song);

```

I see there was a question on StackOverflow, and the answer looks like he is on a Windows PC. Maybe that will help get you there.

### Playlist

You mention wanting a playlist, well MediaPlayer.Play can also take a SongCollection, and it will just loop through each song.

# Answer
> 1 votes
As a follow up on this other question you can load all the mp3s in a directory into a `Song` list with:

```
var songs = Directory.EnumerateFiles(directory, "*.mp3")
            .Select(file => Song.FromUri(file, new Uri(file)))
            .ToList();

```

You can look in the Music folder by setting directory to the following:

```
string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);

```

There's also a known bug where `Song.FromUri` will throw an exception when trying to load a file that has spaces in its name. See this answer on stackoverflow for a workaround using reflection to call the internal constructor directly.

---
Tags: xna-4.0, music
---


# Question
Title: Shooting intervals with variable framerates
lets say i have a gun which fires at a rate of 10 shots every seconds.

so i every gameloop frame, i check if the necessary time has passed and instantiate a new shot.

now what if the framerate of the game actually drops below 10 fps. then the player will have a disadvantage because his gun doesnt fire accordingly anymore.

what is the usual workaround of this problem?

thanks!

# Answer
> 3 votes
A workaround is to determine how many shots need to be fired as a float and accumulate remainders.

Normally your loop is running fast enough that the shots needed is 1.0; sometimes your loop is slow and the shots needed is 1.2 and you accumulate 0.2 for that frame. Once you've accumulated more than an extra 1.0 then simply launch it as an extra shot that frame and subtract 1.0 from the accumulator.

Keep calm and accumulate on.

A second workaround would be to cause the one shot to have "shot * needed" power, so that on a normal frame your shot does 1.0 damage but on slow frames your shot does 1.2 damage.

# Answer
> 1 votes
Game loops can deploy mechanisms to prevent logic from not being executed if the other parts of the loop take too long. For example, if you'll lock your game logic at 30 frames per second and inside of the loop you check if it's the time to run the logic frame, then instead of putting it in an "if" statement, you put it in a loop that'll have a "max frame skip limit".

The idea is that if your game is going to render slowly then the next iteration the game logic will "catch up" by executing x amount of times instead of just 1.

If you have your bullet shooting tied to a timer then you can also put the logic that checks if it's the time to fire inside of a loop and just try to make up for frame rate drops.

Now, in general, this doesn't matter as much as you describe it. The player isn't REALLY at a disadvantage here. Everything needs to be processed inside of the game loop. If the player's gun doesn't fire, then the AI's gun doesn't fire aswell. So it's all about the implementation. Either you consider frame rate drops when dealing with AI and the player or neighter.

# Answer
> 0 votes
I would do something like this in Update(...):

```
_toFire += 10f * elapsedSeconds;
while (_toFire >= 1f)
{
    _toFire -= 1f;

    Bulet bullet = new Bullet(/*start posittion (gun position)*/, /*bullet speed*/);
    bullet.Update(_toFire);

    _bulletList.Add(bullet);
}

```

In my pseudo code I add as many bullets as should be in game by the time passed between the updates. Then I adjust their positions with update.

Something like that should do ...

---
Tags: timing
---


# Question
Title: XNA: weird effect by matrixTransform of spriteBatch on isometric tile
I wrote a `Camera` class that contains `Matrix` (for zooming and moving around). When I zoomed it with any zoom scale other than 1, some isometric grids becomes visible on each of my isometric tile.

```
//Camera.cs
//Producing the matrix from previously set Zoom and Location
        public static void Update()
        {
            Transform =         Matrix.CreateTranslation(Location.X, Location.Y, 0) *
                                Matrix.CreateScale(Zoom,Zoom,1);
            InverseTransform =  Matrix.Invert(Transform);
        }

//Game.cs
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Camera.InverseTransform);

                /* Some Drawing */

            spriteBatch.End();

```

PS: Actually, I really want these grids to be visible for zoom scale of 1.0f too. Having these grids make my game looks more like a tile-based game.

Before Zoom (Scale = 1.0f):

After Zoom (Zooming in):

After Zoom (Zooming out):

Zooming very close (Grid line appears to be more than one pixels):

# Answer
> 0 votes
Could be aliasing, I mean that at some magnifications the sampling of the grid just happens to skip over the lines you want.

Is it possible to make your grid line thicker than one pixel?

---
Tags: xna, sprites, isometric
---


# Question
Title: Collision with tile corners/seams in 2D platformer
There seems to be a lot of somewhat related questions answered already, but none I read answered my exact problem.

I have a 2D platformer whose world is made entirely out of tiles that are in a regular grid. When there is a collision, I just move the character to the position he was in prior to the collision and it works well enough for me.

The character can fly/slide in the world, so I also want to set the speed towards the collided tile to zero. **Here lies my problem.**

At the moment the only way to do this I can think of is to check the difference between the character position and the center of the tile. If (the absolute value of the) x-difference is greater, then it is a horizontal collision. If y-difference is greater, then it's a vertical one. However, as the character is sliding horizontally on tiles, from one tile to another, sometimes he stops at the seam of the tiles because momentarily the x-difference becomes a tiny bit greater than the y-difference (due to float inaccuracies I suspect). I don't know if it's possible to change this algorithm to fix this, or if I need a new one. Any algorithm will do, as long as it fulfills the "requirements" stated above.

If at all possible, I want to treat the x- and y-collisions identically, because the movement is not just walking horizontally.

Image illustration: https://i.stack.imgur.com/URkoV.png

# Answer
> 5 votes
This is a really common problem, and I'd be very surprised if it hasn't been answered several times already.

Short version of several potential fixes:

1) Ignore internal edges between tiles using flags. For each tile, set a flag for each of its four sides indicating whether that side is external (adjacent to an empty cell) or not. Then only do collision tests against edges that have the flag set. So in your example, since the edge between the two floor tiles is an internal edge, you would not perform the x axis test against that edge. There is a great series of articles by the N+ author on metanet that takes this technique a bit further, with working Flash demos.

2) Collapse external edges into a simplified set of lines. This is a bit more complicated that the previous method, but can be more flexible. Essentially, find all the external edges and convert them into line segments. The find all line segments that share a vertex and have the same normal an merge them into a single line segment. Then switch your collision detection to use AABB to line segment tests. The result is that you won't have any internal edges to test against in the collision data structure. Also, this makes it easier to add arbitrarily shaped tiles later.

3) A simple but error prone method is to just special case a lot of your collisions logic. This is what some old school classic platformers did. It's often sufficient to take the direction of movement and then do collision detection against the "most perpendicular" of the x or y axis, then do the other. For instance, if the player is mostly moving horizontally, first do collision along the y axis and resolve, then against the x axis. Include a small bit of tolerance. Result will be that the player is pushed out of the floor enough that the problematic internal edge collision falls within the error tolerance and is ignored.

4) use hot spot collision detection. This is what most old school platformers did. I don't care for this method myself and it takes some work to explain (although it's very simple to implement), but Google can likely find a few articles on it for you. You may find this method best suits your needs if youre aiming for simplicity.

---
Tags: 2d, collision-detection, platformer, collision-resolution
---


# Question
Title: Will a polled event system cause lag for a server?
I'm using a library called ENet. It is a reliable UDP library.

The way it works is a polled event system like this:

```
  ENetEvent event;

    /* Wait up to 1000 milliseconds for an event. */
    while (enet_host_service (client, & event, 1000) > 0)
    {
        switch (event.type)
        {
        case ENET_EVENT_TYPE_CONNECT:
            printf ("A new client connected from %x:%u.\n",
                    event.peer -> address.host,
                    event.peer -> address.port);

            /* Store any relevant client information here. */
            event.peer -> data = "Client information";

            break;

        case ENET_EVENT_TYPE_RECEIVE:
            printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
                    event.packet -> dataLength,
                    event.packet -> data,
                    event.peer -> data,
                    event.channelID);

            /* Clean up the packet now that we're done using it. */
            enet_packet_destroy (event.packet);

            break;

        case ENET_EVENT_TYPE_DISCONNECT:
            printf ("%s disconected.\n", event.peer -> data);

            /* Reset the peer's client information. */

            event.peer -> data = NULL;
        }
    }

```

It waits up to 1000 milliseconds for an event. If I'm hosting say 75 event driven card games and a lobby on the same thread as this code, will it cause any problems.

If my understanding is correct, the process will simply sleep until there is an event, when there is one, it will process the event then come back here where potentially 5 or so events have queued up since so enet\_host\_services would return right away and not cause lag.

I have been advised not to use multiple threads, will that be alright like this?

Thanks

# Answer
> 2 votes
If your entire game is driven by events that come in via `enet_host_service`, then no, you won't get any delays as a result of this approach. The server may keep sleeping for 1 second but nothing is happening in that period so it doesn't matter.

If however you have any other timed action which happens regardless of which events come in, then they will presumably live outside that switch statement and will have to wait for external events to trigger before the action can execute.

If you are in that situation and do have some other timed events, you can always reduce that 1000ms delay to something smaller, like 50ms, so that the timed events can be attended to fairly regularly. This is unlikely to have a significant negative effect on performance.

Note that you need to wrap the above code in another loop, as `enet_host_service` will return zero as soon as it manages to go an entire second without getting a message.

---
Tags: c++, game-design
---


# Question
Title: Creating movement path displays in a top-down 2d RTS
My game is a top-down 2d RTS coded in C# using SFML's libraries. I want that during unit selection, a unit will display it's movement path on the map. Currently, after the path is computed as a list of directions ({left, up,down, down, down, left}, as an example), it's sent to the graphical component to create it's UI equivalent, and here I'm having some problems. current, these I've checked three ways to do it:

1. compute the size of the image (in the example above it'll be a 3\*2 rectangle) and create an invisible rectangle, and then go over the directions list and mark each spot with a visible point, so as to get a continous line. This system is slightly problematic because of the amount of large images that I need to save, but mostly because I have a lot of fine detail onscreen, and a continous line obstructs the view.
2. again, compute the size of the image, but now create several (let's say 4) invisible images of that size, and then instead of a single continous line I'll switch between the four images, in each will appear only a fourth of the spots, in a way which creates a path animation. This is nicer on the eye, but here the memory demands, and the amount of time needed to compute each such image-loop is significant.
3. Just create a list of single markers, each on a different spot on the path. This is very quick & easy on memory, but too sparse.

Is there a simple or resource-light system to create path-animations?

# Answer
You could do something similar to #3, but create a very small marker for each tile in the path in order. Then you could display the markers as arrows pointing to the next location in the path. That way, you'd only have to have one (tiny) image, which could be rotated and blitted to multiple locations, while the path is still very clear.

Example:

```
. . . . x .
# # # # ^ .
. . > > ^ .
. . ^ # # #
. . ^ < s .
. . . . . .

```

In your example the unit turns on a dime and partially retraces it's steps. I wouldn't expect that to be ordinary behavior but if it occurred you could just blit multiple arrows to the same tile.

I'd make the arrows very small and thin and a bright color so they stand out without obscuring your detail. Also, you should only display the path for the selected units, in my opinion...tons of paths crisscrossing your terrain could be confusing, besides slowing the game down.

Good luck with your game!
> 2 votes

---
Tags: c#, rts, sfml
---


title: locking on target

text:
# Question
Title: locking on target
I'm having problem with locking one object on another. Lets image an turret which always targets flying plane. I come to this solution:

1. Compute `yaw = atan2(z2-z1, x2-x1)`
2. Compute `pitch = atan2(y2-y1, z2-z1)`
3. Rotate

What do you think about such method? Is there any "faster" way without using `atan2`? Can I achieve same effect with just quaternions operations?

# Answer
To get an object A to point towards a point B, then it's not difficult.

```
Vector current_heading = non_rotated_heading_of_object * object->rotation;
Vector target_heading = (target_position - object->position).normalize();
Vector axis = current_heading.cross(target_heading);
float angle = std::acos(current_heading.dot(target_heading));
Quaternion rotation = rotateAngleAxis(axis, angle);

```
> 1 votes

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


title: XNA:Rectangles Movement Behavior

text:
# Question
Title: XNA:Rectangles Movement Behavior
im trying to create simple pong game, and learning some XNA. im creating for each paddle 3 rectangles, who represnt the collision when the ball hit them, so i can dicide where to throw the ball back.

here is the function that i create the rectangles:

```
List<Rectangle> collisonRectanglesList = new List<Rectangle>(3);
      private void creatCollisonRectangles()
        {
 smallPaddleWidth = collisionRect.Width;
             smallPaddleHeight = collisionRect.Height / 3;
            for (int i = 0; i < collisonRectanglesList.Count; i++)
            {
                if (collisonRectanglesList[i] != null)
                    collisonRectanglesList.RemoveAt(i);
            }
             collisonRectanglesList.Add(new Rectangle((int)position.X + smallPaddleWidth, (int)position.Y + smallPaddleHeight * 2, smallPaddleWidth, smallPaddleHeight));
             collisonRectanglesList.Add(new Rectangle((int)position.X + smallPaddleWidth, (int)position.Y + smallPaddleHeight, smallPaddleWidth, smallPaddleHeight));
             collisonRectanglesList.Add(new Rectangle((int)position.X + smallPaddleWidth, (int)position.Y , smallPaddleWidth, smallPaddleHeight));

        }

```

now i want this to follow the paddle it self so i put this function in the update method and made a simple texture so i can draw them and see where they are on the screen.

my problem is that when i call the `creatCollisonRectangles()` 1 of the rectangles paint it self in the middle and not in the place it should be.

any idea why?

this is when im not calling it in the Update method:

and this when i do:

(sorry for my english)

# Answer
> 1 votes
It looks like you're generating new collision rectangles every update and this probably means that you're a) overriding the rectangle you mean to draw or b) trying to access a rectangle which no longer exists. Creating the rectangles once then updating their positions would fix that (not to mention be much more efficient that allocating new rectangles every fraction of a second ;) ).

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


# Question
Title: What are the downsides of only explicitly informing the player of *success*?
I'm working on educational software and trying to increase Engagement ("fun").

Clear Progress toward a Goal (one of the tenets of Engagement) would suggest we need to let the *player* know how they are doing. But we don't want the player to become demoralized. (These "players" have brain injuries, and so can become very demoralized easily.)

So I'm thinking that we'll want to only explicitly show forward progress ("You 'leveled up'"), but we wouldn't have "lives" (because you can "lose" them).

**Clarification**:

Think of this as Education "Tutoring" Software (sort of like the Kahn Academy) We already give them feedback when they get an answer wrong. We also help them get the right answer.

But when they do very well they Graduate to a higher level. If they do very well for a long time they get some sort of award/recognition that they are doing exceptionally well.

What I'm wondering is if they have a sustained period of poor performance, should we also give them recognition (obviously something kinder than "Hey, you suck"), so that this "failure recognition" doesn't really give them more *information*?

This is the roman emperor giving a thumbs down (the Gladiator already knows how he did in the battle).

**Any downsides to that?**
(I guess one might be that they lose faith in feedback from the game because it's not telling the whole story. Sort of like if a parent only gives you praise, you might start to think they're saying it to be nice.)

# Answer
> 6 votes
> What I'm wondering s if they have a sustained period of poor performance, should we also give them recognition "hey, you suck" (Obviously something kinder).

There's no point to that. Indeed, if you're too clever about it, you can induce the wrong behavior. Just look at YouTube for "death videos" from King's Quest games. People want to see what the narrator says about each death, because Sierra spend a lot of time and effort making them unique and using horrifically lame puns.

I'd say the best way to handle this is to ignore it. Particularly in education software.

---

It all really depends on how you do it. You didn't say what your "game"play was, so it's hard to give good advice.

The best way to look at it is to compare modern game design elements to elements from days past. Mazes are a great example.

In old games, mazes, without any form of mapping system, were basically just time wasters. There would be something of value somewhere, maybe several somethings. But there would be a lot more dead-ends than there were actual somethings. So a lot of time is wasted exploring locations that yield nothing.

In modern game design, "mazes" aren't mazes anymore. If you can get somewhere, then in all likelihood there is *something* of value there. It may not have been what you were looking for, but it is something.

I would suggest looking towards that kind of game design, where the difference between "failure" and "success" is blurry. It can have downsides. For example, if one place causes forward progress out of that mazes (or that area within the larger maze), then players may actually be disappointed to find process. "Success" in this case is failure to them; they wanted the stuff they would find in side passages.

# Answer
> 5 votes
Outside of any psychological downside as you have mentioned, the biggest issue I can see from a gaming perspective is that the game play could potentially get stale if its designed to remove all negative feedback. If I'm not being challenged in a game or if your game comes across as too easy I might get bored with it quickly.

Lots of people use failure as a motivator to get better at and as such, replay or keep playing a game. You really have to find that balance between challenging and frustrating so that the players keep playing because they want to get better (or complete the game), versus them quitting because they are frustrated.

# Answer
> 5 votes
Absolutely. Half of learning is failing and discovering what NOT to do (hell probably more than half of learning is failing).

If they do something wrong, they need to know it otherwise they will never learn it is wrong.

This will sound heartless, but they need to deal with it. This is where tough love comes into play. Sometimes you have to force someone to do something they would rather not do until they get it. Overcoming a major obstacle is a major confidence booster. As time goes on, they will learn to persevere.

Another side effect will possibly to teach them they can do no wrong or that doing something wrong will have no ill consequences, which is hardly the case.

# Answer
> 0 votes
> What are the downsides of only explicitly informing the player of *success*?

There are no downsides to only using positive reinforcement of player progress.

Many popular games don't have have a concept of losing or failing.

Look at simple games like Bejeweled Blitz that rewards you for every match you make in 60 seconds, or complex games like World of Warcraft where there is no such thing as game over, just more loot on the horizon.

> "lose faith in feedback from the game because it's not telling the whole story"

Why is failure a part of the story in your mind? Just let players keep clicking until they they win!

If your game only provides positive feedback, and players have clear goals and understand how to achieve them, they will enjoy your game.

Failure is an obstacle to player enjoyment, not a pre-requisite.

---
Tags: game-design
---


# Question
Title: DevIL image library isn't loading my image
This is the first time I've had this problem, my code just won't load the images I need it to.

Here is my first function for loading the image into data:

```
    void C_Resource_Loader::v_Create_Image(std::string filename,int nID)
{
    //create image and bind to it
    ilGenImages(1, &image[nID]);
    ilBindImage(image[nID]);

    //check if DevIL successfully loads the image
    success = ilLoadImage(filename.c_str());
    if(success)
    {
        success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
        if (!success)
            SDL_Quit();
        //create texture and bind to it
        glGenTextures(nID,&texture[nID]);
        glBindTexture(GL_TEXTURE_2D,texture[nID]);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
        ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
        ilGetData());

        ilDeleteImages(nID, &texture[nID]);
    }
}

```

and here is my code for putting the image on the screen:

```
void C_Resource_Loader::v_Apply_Image(int nID, int pn_X, int pn_Y, int pn_Depth)
{
    glPushMatrix();

    //bind the image so it can be textured
    glGenTextures(1,&texture[nID]);
    glBindTexture(GL_TEXTURE_2D,texture[nID]);

    //move the image to the set x and y
    glTranslatef(pn_X,pn_Y,-600);

    glBegin(GL_QUADS);

    glTexCoord2i(0,0);
    glVertex3f(0,0,pn_Depth);
    glTexCoord2i(0,1);
    glVertex3f(0,32,pn_Depth);
    glTexCoord2i(1,1);
    glVertex3f(32,32,pn_Depth);
    glTexCoord2i(1,0);
    glVertex3f(32,0,pn_Depth);

    glEnd();
    glPopMatrix();
}

```

Is there a major problem with it, because this code should work, I've used it many times before...

# Answer
You are calling `glGenTextures` right before drawing your quad. This should be only called when loading the texture data, since this creates a texture reference in the GPU for use by your code.

And check you are calling `glEnable(GL_TEXTURE_2D)` somewhere in your code so 2D texturing can be used.
> 1 votes

---
Tags: c++, opengl, image, loading
---


# Question
Title: Initializing entities vs having a constructor parameter
I'm working on a turn-based tile-based puzzle game, and to create new entities, I use this code:

```
Field.CreateEntity(10, 5, Factory.Player());

```

This creates a new Player at \[10; 5\]. I'm using a factory-like class to create entities via composition.

This is what the CreateEntity method looks like:

```
public void CreateEntity(int mX, int mY, Entity mEntity)
{
    mEntity.Field = this;
    TileManager.AddEntity(mEntity, true);
    GetTile(mX, mY).AddEntity(mEntity);
    mEntity.Initialize();
    InvokeOnEntityCreated(mEntity);
}

```

Since many of the components (and also logic) of the entities require to know what the tile they're in is, or what the field they belong to is, I need to have mEntity.Initialize(); to know when the entity knows its own field and tile.

The Initialize(); method contains a call to an event handler, so that I can do stuff like this in the factory class:

```
 result.OnInitialize += () => result.AddTags(TDLibConstants.GroundWalkableTag, TDLibConstants.TrapdoorTag);
 result.OnInitialize += () => result.AddComponents(new RenderComponent(), new ElementComponent(), new DirectionComponent());

```

This works so far, but it is not elegant and it's very open to bugs. I'm also using the same idea with components: they have a parameterless constructor, and when you call the AddComponent(mComponent); method in an entity, it is the entity's job to set the component's entity to itself.

The alternative would be having a Field, int, int parameters in the factory class, to do stuff like:

```
new Entity(Field, 10, 5);

```

But I also don't like the fact that I have to create new entities like this. I would prefer creating entities via the Field object itself.

How can I make entity/component creation more elegant and less prone to bugs?

# Answer
If entities must have positions (which is implied, as your `CreateEntity()` call takes the position as a parameter), why not put the position into the Entity itself, and then pass the x,y coordinates to the Player Factory directly?
> 2 votes

---
Tags: c#, entity-system
---


title: Collision, then what?

text:
# Question
Title: Collision, then what?
I know how to check collision for example 2 `spheres`. But my question is how do I use the collsion response in a good way?

How do I make my character unable to walk in to the `Sphere`? I've got to the point where my game send a `PrintLn` when `isCollided` and it works but my character just walk through it.

How should I do?

Cheers!

# Answer
> 1 votes
I guess the best approach for this situation would be to use physics.

Take a look at this 2D collision.

Basically, if you want a realistic collision, you have to give a concept of mass to your objects, and, after calculating that they collided, apply the respective equations.

If objects are not spheres, then the problem is way more complicated...

# Answer
> 0 votes
Without knowing much about your environment, i would say: simply put your character into a not moving (aka stopped) state. That can be achieved by setting his speed to 0 or may require more complex operations :D

---
Tags: 3d, collision-detection, mathematics, terrain
---


# Question
Title: Would it be a good idea to offload tasks like navigation to the GPU?
So I was reading through my copy of GPU Pro 2 and I came across a chapter for building a rendering pipeline for real-time crowds. The implementation uses render targets on the GPU to update agents and finite state machines while also performing frustum culling and level of detail sorting. With this approach, the test case in the chapter is able to easily render about 8,000 characters walking in a crowd.

My question is have any games started taking advantage of the GPU for task other than rendering and physics such as game object updating and AI? And if so, are there any conceivable disadvantages to their implementations?

I ask this because I'm thinking about going this route with my game using D11 DirectCompute to create and simulate large scale space battles. Off the top of my head, I think the GPU would at least be a good tool in calculating and blending steering behaviors.

# Answer
I see no reason not to re-promote one of my old answers: Are there any benefits for using the CPU instead of the GPU?

On top of that it's worth considering that we don't party like it's 1999 any more, 20 000 polygons on screen definitely looks better than 10 000. But if it's 500 000 polygons vs. 200 000, or fancy dynamic shadows vs. blob shadows, or 2000 filler NPCs vs. 500, no one really cares. If you set it up side by side and show people the difference they will of course say that one is better than other other. But if they have to judge a game on it's own the impact of such details is negligible.

Is figuring how to do a specific task on the GPU worth your time? If the gain is simply more filler NPCs, the answer to that question is most likely no. Combine it with the points about being able to run on lesser PCs and the doubt is blown away.

I'm not saying that game programmers should never consider running something unconventional on the GPU, but there are so many other things worth spending time on that a well made list of priorities will almost always have something more important.
> 8 votes

# Answer
There are reasons to avoid using the GPU. For many "AAA" games, even high end GPUs are already being completely utilized by actual rendering work that there isn't any GPU computing time or memory to spare on other tasks.

For games with less demanding graphics, it may be desirable to have less demanding hardware requirements. If you don't need a powerful GPU for graphics, wouldn't it be nice of people with low end or integrated GPUs could run your game? If you're selling your game as an indie dev, the segment of the market that has nothing but an Intel GPU (and not the very latest Ivy Bridge) can make up a sizable chunk of your sales.

Lastly, keep in mind that the GPU has some latency to it. It can take upwards of several frames to get the results of any computation back. If you're not very careful, it's easy to stall both the CPU and the GPU during data transfer to and from the GPU. Even if you are careful, this can be a problem. For even many graphics related tasks, it's not at all uncommon to unload some processing to the CPU that the GPU might be better at. E.g., occlusion queries can often be computed on the CPU faster than it would take to send and receive the request to the GPU, even though the GPU could do the actual computations much faster. Modern CPUs are often under utilized by games, and there's a lot of spare processing power to play with if you're comfortable writing threaded code.

Generally, the GPU should be considered for very large batches of highly parallel data processing.

Specifically answering your question: yes, the GPU can and has been used for AI processing. Particularly for things like terrain analysis, occlusion queries and ray tests, and some navigation. However, it's applicability is very dependent on the specific algorithm and data set used and the desired hardware requirements.

You are best off writing your code CPU-side (the tools are more mature, debugging is far easier, and more people could run your game) and moving it to the GPU only if you truly can't get it to run with adequate performance on the CPU.
> 4 votes

# Answer
At its core, this is really just an optimization question.

If you can do more with your GPU than with the CPU, then it's a good idea. If it isn't, then it isn't.

That's not to say that you might not learn a lot by trying to make GPU-friendly code, but personally I wouldn't start with that unless you build a prototype with the numbers of enemies you think you would want and start running into performance issues.
> 1 votes

---
Tags: gpu
---


# Question
Title: Can you store negative numbers with XNA HLSL?
I am trying to make a ripple effect with a HLSL shader, it works so far but I need to output negative numbers and that won't work for the calculations. Is there some way to do this with the `SurfaceFormat` class? By the way I am rendering 2 `RenderTarget2D` classes. This is how I calculate it:

```
float4 add = float4(0,0,0.5,0);
float4 input = tex2D( BaseSampler, Tex);
float4 cur = tex2D( RippleSampler, Tex);
float curY = 0;
float curX = cur.x;
float tempCurY = cur.y;

curY = (tex2D( RippleSampler, float2(Tex.x - pixelSizeX, Tex.y)).x + tex2D( RippleSampler, float2(Tex.x + pixelSizeX, Tex.y)).x + tex2D( RippleSampler, float2(Tex.x , Tex.y - pixelSizeY)).x +  tex2D( RippleSampler, float2(Tex.x , Tex.y + pixelSizeY)).x) * 0.5f - tempCurY;
curY *= damping;

if(curY < 0.01f){
    cur = float4(curX,curY  + input.x,0.5,1);
}else{
    cur = float4(curX,curY,0.5,1);
}

return cur;

```

# Answer
> 2 votes
The trick is to encode the negative number as positive one, by transforming it into a different positive range.

For instance if you need to store values in the `[-1,1]` range in the texture, you'd start by mapping that into the `[0-1]` range before rendering to the texture.

You can do this for instance, by taking the original number, adding one to it and then dividing by two.

```
float originalValue = /* some number between -1 and 1 you want to store in the texture */
float encodedValue = (originalValue + 1.0f) * 0.5f; /* now it's between 0 and 1 */

```

Then inside your pixel shader, after reading from the texture, convert it back into the original `[-1,1]` range by multiplying by two and subtracting by one.

```
float encodedValue = /* value in 0 to 1 range read from the texture */
float originalValue = encodedValue * 2.0f - 1.0f; /* now it's back between -1 and 1 */

```

---
Tags: xna, shaders, hlsl
---


# Question
Title: physics.addBody() with custom shapes in Corona SDK
Does the physics.addBody() only work with Circles and Rectangles? Or is it possible to physics.addBody() on vector shapes or sprites or with masks or something?

# Answer
> 2 votes
It works with more than just circles and rectangles. To be more specific,

> \[physics.addBody()\] Allows you to turn any Corona display object into a simulated physical object with one line of code, including the assignment of physical properties.

The full explanation, along with examples including a rectangle, circle, and polygon, can be found here.

# Answer
> 1 votes
If you want an irregular physics object, you have to specify the x and y coordinates of the physic body. Complicated, but possible.

Or you can use a third-party tool like PhysicsEditor.

---
Tags: collision-detection, corona-sdk
---


# Question
Title: Creating an object in javascript with unity (unityscript)
So I have a ton of experience with JavaScript (its what I do for a living) but I am new to unity. I have built a game engine in javascript but now want to move it over to unity. I have been trying to implement my player class but am running into this error.

I have a getter function for my level\_up stats. and inside of my level\_up function I call that getter function and store it now I know this would work in normal javascript but its not in unity and I have having a heck of a time googling any information on objects in unityscript. Here is the relevant code:

```
function level_getter(){
    return {base_level_exp : float , lvl_exp_modifier : float , current_level : int};
}

function level_up(){
    var level_object = new Object();
    level_object = level_getter();

    level_object.current_level += 1;
    level_object.base_level_exp = level_object.base_level_exp * level_object.lvl_exp_modifier;

    level_setter(level_object.base_level_exp, level_object.lvl_exp_modifier, level_object.current_level);

}

```

I guess my first question is, is it even valid to return an object like that in unityscript?(in the `level_getter()` function). If its not valid what do people suggest I do instead. Set a getter function for each `var`? My second is how do I declare `level_object` so that it can accept the return if it is valid, and so that I can access the members of the object.

I have been looking around at tutorials and google for several hours now and have found nothing to clear up my confusion over objects in unityscript. So any help would be appreciated.

# Answer
I'm not an expert in unityscript but I'm relatively familiar so i'll make an attempt. Im also at work and don't have access to unity so any code here may not be 100% =-)

While I'm not totally fluent in JS, it looks like you are trying to use something like JSON to pass data and while unityscript syntax is close to JS, I don't believe it works the same way.

I think what you will want to do is to create an object of a type "PlayerStats" or soemthing like that to keep track of the player info and instead of `var level_object = new Object();` you would do `var level_object : PlayerStats = FindObjectOfType(PlayerStats);`

That should give you access to all of the member vars in PlayerStats and allow you to mess with them.

Since you are new to unity, might i suggest the tutorial sets here: http://www.burgzergarcade.com/hack-slash-rpg-unity3d-game-engine-tutorial \- They are pretty extensive and show a lot of how to pass data between objects.
> 1 votes

# Answer
Be careful, Unityscript is not Javascript. Here an example on how to solve your Problem:
***Your level object:***

```
class PlayerLevel {
    public var base_level_exp:float;
    public var lvl_exp_modifier:float;
    public var current_level:int;
}

```

***Your levelup thing:***

```
function level_up() {
    private var level_object:PlayerLevel = new PlayerLevel();

    level_object.current_level += 1;
    level_object.base_level_exp = level_object.base_level_exp * level_object.lvl_exp_modifier;

    level_setter(level_object);
}

```

This is just an example, it is untested and should just illustrate how to create custom objects. I hope I could help you to see some differences between Javascript and Unityscript.

You might want to read the following article: Head First into Unity with UnityScript
> 1 votes

---
Tags: unity, javascript, objects
---


# Question
Title: Stress testing a game server without users?
I'm working on a card game and its server. There will be a lobby with many tables and many players. The only issue is, how can I see how it might handle 100's of concurrent users without hundreds of concurrent users?

How is this sort of thing usually done?

# Answer
> 23 votes
Two words: headless client.

Basically it's an AI driven client that's had the all graphics bypassed so that you can run many multiples of copies on a machine, you can even run them on servers because you never initialize the graphics at all.

Above all those clients is a supervisor that is responsible for starting, monitoring and stopping all the clients to test, log and re-run after client crashes.

# Answer
> 8 votes
I think you are worried about the wrong things Milo. I see from your other questions you are planning on writing the game is C++.

Even a not very well coded sever written in a scripting language would be able to handle 100's if not 1000's of requests with out apparent lag in a card game.

These kinds of technical details are probably not going to be a big problem. If they do become a problem it would only be a day or two of optimization or moving things around a little. But only after the game is finished and only after you have identified what exactly the problem is..

Writing a headless client now to simulate lots of uses is a waste of time.. focus on the really hard problems like..

1. actually finishing your game and getting it online and
2. finding the 100's of people who want to play your game simultaneously.

---
Tags: c++, server, testing
---


# Question
Title: Does Unity Pro Play Nice With 'Small' Teams
Does anybody know how well Unity Pro plays well with-in small teams? Our team makeup is 2 programmers, 1 audio, and 2 graphics peps.

How easy is it for somebody to mess up a Unity project? The graphics and audio people will likely only have a simplistic knowledge of Unity, and mainly in regards to only there area.

Do the graphics/audio even need access to the Unity editor?

I've seen the Asset Server and it seems like a *very* bare bones versioning system.

Before people start telling me that they should just learn it (as I agree) this is a rather last minute student prototype project.

# Answer
> 2 votes
Generally, it's easy for someone to mess up *any* project, Unity or not. What matters most is that people learn how their project works and what *could* mess it up.

Unity, on the plus side, is very easy to learn. I've worked on three Unity-based projects, all with small teams of 5-10 people, and I've never seen anyone mess the project up... much. I mean, there were some misunderstandings, wrong files committed to source control, etc; but nothing that couldn't be fixed in half an hour tops.

Unity is pretty easy to use, and one of its strengths is that it allows your audio/graphics guys work in the same editor as everyone, and easily test their work in-game. Being able to immediately see one's work ingame is a big boost to productivity. Also, Unity is *very* easily extended. You'd probably find yourself coding dozens of little tools to help both programmers and artists with their work, and this will probably add up to big savings.

Regarding source control, don't even think about Asset Server, it sucks (AND costs money too). Since 3.5 Unity supports external source control even in free version; and also text-based asset format that is more-or-less merge-friendly. I've successfully used SVN with Unity projects, and I believe Hg or Git would work like a charm too.

# Answer
> 0 votes
I have myself been using Unity for two smaller projects now on teams of 5 people, and it works pretty sweet. By putting up the asset server your team can collaborate well with each other and version control works swell as well. With that in mind it is important that you maintain communication even when using Unity Asset server as it is still possible to mess things up a bit, though the Unity Asset server history can resolve many issues as well.

You mention that your a team consisting of programmers and a graphic/audio guys. In our current project, we are three programmers and an audio guy (We make audiogames), and our sound guy just spits out audioclips like a fountain into our Project with ease and without any issues.

The biggest problem we have is when the programmers are changing the scene (We only use one scene), though it is always quickly resolved.

# Answer
> 0 votes
We use Unity Pro and Mercurial for version control and things works pretty well. We didn't feel we needed the Asset Server.

One thing to notice is that before Unity 3.5, we had problems with people working with the same scene: those files were binary, therefore there were no way to merge. Now, Unity provides a YAML-based asset serialization option, so everything can be easily merged. But that option is for Pro only.

Our artists doesn't use Unity. Sometimes, an artist use Unity do make some things, but that is rare. One example is the terrain. But everything else is made with other software and imported by a programmer.

# Answer
> 0 votes
> How easy is it for somebody to mess up a Unity project?

If you have a lot of data defined via the Inspector, and therefore stored in a scene, it's quite easy for someone to make a change that potentially conflicts with someone else's. If you use the text-based scene format then it's possible that your source control software can merge the changes, but not guaranteed. Be prepared to have to resolve merge conflicts to continue.

If you don't use version control, then people will tend to overwrite each other's work on a regular basis, because of the shared scene data. One way around this is to avoid storing anything in the scene and instantiate everything from code - but going down this route starts to lose you many of the benefits of Unity.

> Do the graphics/audio even need access to the Unity editor?

This depends how much work you want the programmers to do, and on the type of project you're making. The art and audio people can just export assets and programmers can import them, if you like. But some teams prefer the artists to check their assets work properly in the engine, and to have the audio people place the ambient sounds in the correct locations and check the relative levels as they walk around, etc.

---
Tags: unity
---


# Question
Title: Using XBOX controllers on PC for an XNA game
Does anybody know how to do this? I have been trying to figure this out with no luck.

# Answer
This? I think the GamePad stuff works on Windows last time I tried it.
> 5 votes

# Answer
It should work pretty easy. I'm using an xbox 360 controller plugged into my windows machine as my main gaming controller, and to make an XNA project use it all I had to do was:

```
GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);

float movement = gamePadState.ThumbSticks.Left.X * MoveStickScale;

if (Math.Abs(movement) < 0.5f)
                movement = 0.0f;
if (gamePadState.IsButtonDown(Buttons.DPadLeft)){
                //do something
}
if (gamePadState.IsButtonDown(Buttons.LeftShoulder){
                //do something else
}

```

and so on. Have you tried testing that the 360 controller works properly with your machine? Like, with other programs/games? Maybe you've just got a driver problem, but I think windows vista and 7 have the 360 drivers by default. (I'm using XP, had to install them)

Try looking at these code samples: http://create.msdn.com/en-US/education/catalog/sample/platformer

http://create.msdn.com/en-US/education/catalog/sample/input\_sequence\_sample
> 11 votes

# Answer
You need the "XBox Controller For Windows". As far as I know the controller itself is the same, however, you get an adapter that can be used with any XBox controller device. Either that, or the device just ships with the driver CD.

I would go with Zaphod42's advice (just plug the thing in if it's a standard USB device); and if that doesn't work order one online.

Not 100% sure because I don't own an XBox.
> 1 votes

# Answer
You need one of the Microsoft Xbox 360 Wireless Gaming Receivers for the wireless pads.
> 0 votes

---
Tags: xna, xbox360, pc, controllers
---


# Question
Title: How to apply impulse to a body to make it fly away?
I'm playing around with jbox2d and can't really make a body "fly away" as if from an explosion.

From what I have found on the net, making the body fly away from the world center (0,0), should have been something like that:

```
b.applyLinearImpulse( new Vec2(0,0) , b.getPosition() );

```

But really it just doesn't do anything, any idea why? Also how do I change the strength of the impulse, like if it want to make it fly skyhigh or just move a bit?

# Answer
The first argument of applyLinearImpulse is the vector which is the strength of the force/impulse. So just change it to something else rather than 0,0 and your object should fly.
> 7 votes

---
Tags: box2d, jbox2d
---