# Question
Title: Best method for 2 layer tile based map scrolling
What is the best general approach to implement scrolling for a 2D tile based game?

I need to scroll the map with a constant speed, lets say 2 pixels every frame (like in a top down shooter).

The tiles are 32x32 and the map is quite big, lets say 10 x 300.

There are 2 layers: \- first is the background layer \- second is the forgeground layer with obstacles and enemies

The target plattform is android and I want to use OpenGl.

What is best practice?

a) Draw only the visible Screen all the time (every frame) b) Load complete map into memory and just move the camera

Is there a difference in performance and determining collision etc.?

Thanks for any help!

# Answer
I can't answer specifically for Andriod as I have never done anything for it, but generally you will want to only draw the portion of the map that is visible. It requires much less memory to do it, and shouldn't mess with collision at all. In fact, you will only need to check for collision on the objects you are drawing rather than the entire map.

If you want to have the bottom layer move at a separate speed than the top, the technique is called Parallax Scrolling.
> 3 votes

---
Tags: android, opengl-es, tiles, side-scroller, parallax-scrolling
---


# Question
Title: with XNA 4.0, How can I combine 2 models to make one?
I want to animate Model1 (an aicraft) and I want an object, Model2 (a sphere), to follow it in translation and rotation, as it is a part of this aircraft.

With the following code (I use one or two tutorials to write it) everything seems good when you just change just one angle at the time. The sphere gently follows the aircraft, but if you change more than one angle at the same time, everything goes wrong.

I wonder if it's not a gimbal lock problem? But I use quaternions? Or maybe I haven't understood all this stuff?

My code is below:

```
protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

    // Command input to airplane
        float yokeUpDown = 0.0f;
        float yokeRightLeft = 0.0f;
        float RollRotation = 0.01f;

      //make quaternion rotation matrix of airplane
        Quaternion additionalAircraftRotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), yokeUpDown) * Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), yokeRightLeft) *Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), RollRotation);

    //increase or decrease aircraft rotation
        spacecraftRotation = spacecraftRotation * additionalAircraftRotation;

    // make vector3 sphere angle rotation
        sphereAngle.X = sphereAngle.X + yokeUpDown;
        sphereAngle.Y = sphereAngle.Y + yokeRightLeft;
        sphereAngle.Z = sphereAngle.Z + RollRotation;

    // make rotation quaternion for sphere
        Quaternion additionalSphereRotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), sphereAngle.X) * Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), sphereAngle.Y) * Quaternion.CreateFromAxisAngle(new Vector3(1,0, 0), sphereAngle.Z);

    //relative position of the sphere to the aircraft
        Vector3 translationSphere = new Vector3(-distance_Aircraft_Sphere, 0,0);

        translationSphere = Vector3.Transform(translationSphere, additionalSphereRotation);

        sphereposition = aircraftposition + translationSphere;

        // “VectorToAdd” = direction of the airplane
        Vector3 rotatedAircraftVector = Vector3.Transform(vectorToAdd, spacecraftRotation);

        aircraftposition += moveSpeedAircraft * rotatedAircraftVector;

        sphereposition += moveSpeedAircraft * rotatedAircraftVector;

}
enter code here

```

# Answer
```
I wonder if it's not a gimbal lock problem? But I use quaternions?

```

Yes, your code has a Gimbal Lock problem, since you use Euler Angles. There is a lot of myth out there about Gimbal Locks and how to prevent them. You can also have Gimbal Locks using quaternions, if you use them the way you do. The key is not to store the rotation around each axis separately and not to apply one after another, your code does it here:

```
    Quaternion additionalAircraftRotation =
        Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), yokeUpDown) *
        Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), yokeRightLeft) *
        Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), RollRotation);

    Quaternion additionalSphereRotation =
        Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), sphereAngle.X) *
        Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), sphereAngle.Y) *
        Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), sphereAngle.Z);

```

The solution is not to use Euler Angles. `{yokeUpDown, yokeRightLeft, RollRotation}` and `sphereAngle` are Euler Angles. Rather store them as matrices or quaternions, basically any representation of orientation/rotation will do, except Euler Angles.

Also this code does not do what you want, you can't just add Euler-Angles to combine 2 rotations:

```
    // make vector3 sphere angle rotation
    sphereAngle.X = sphereAngle.X + yokeUpDown;
    sphereAngle.Y = sphereAngle.Y + yokeRightLeft;
    sphereAngle.Z = sphereAngle.Z + RollRotation;

```
> 3 votes

---
Tags: xna-4.0
---


# Question
Title: How to determine the maximum supported level of anisotropic filtering for a graphics card
In software, at runtime, (C++ if it matters), is there a way to find out the maximum level of anisotropic filtering supported by the graphics card?

# Answer
In general you ask your graphics API you're using.

For example if you're using D3D9 you call IDirect3DDevice9::GetDeviceCaps() and then check the MaxAnisotropy value in the D3DCAPS9 structure.

On almost any reasonably modern graphics card the answer will be 16.
> 5 votes

# Answer
In OpenGL, you would (after creating a context and everything) do this:

```
GLfloat maxAniso = 0.0f;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAniso);

```

Of course, this only works when the GL\_EXT\_texture\_filter\_anisotropic extension is available, but since every graphics card has supported this is about the year 2000, I wouldn't worry about it.
> 5 votes

---
Tags: graphics, graphic-effects
---


title: Where to hire 2D sprite artists?

text:
# Question
Title: Where to hire 2D sprite artists?
I'm looking for high quality original 2D sprite collections which are animated where appropriate. (IE not simply collections I can buy, we want original work).

I've had a look online but am struggling to find out where I can hire such people!

* Where do I find such people?
* How much should I expect to pay?

# Answer
> 6 votes
I asked a similar question a while back. It was suggested to me to look at the DeviantArt Job Offers Forum \- Credit to André Paramés

# Answer
> 4 votes
The Lost Garden blog ran a post a few months back where game artists could self promote. Quite a nice a list was generated as a result - List of game artists

# Answer
> 2 votes
The question that lists free existing sprites sets may not give you want you want *directly*, but you might consider using it to track down the authors of some sprites you like the look of and approach them to see if you can work out a contract with them for some custom sprites.

How much you pay probably depends on the artist, the type of work you want, how you want to handle the process of providing/requesting tweaks to the art, et cetera. To give you an example, while I have not contracted with artists for sprites before, I have done so on logos. I ended up paying anywhere from $50 to $300 for the final logo in both high-resolution vector form (and a few bitmap renders) and the rights to use it where and how I needed to. The final logo was the result of about a week, off and on, of back and forth iteration between myself and the artist.

# Answer
> 1 votes
The Gamedev.net Help Wanted forums is great place to search. When I've searched for artists in the past (paid and unpaid), I've usually received replies within a couple of hours.

# Answer
> 1 votes
The pixelation forum, they are dedicated to pixel art and have a jobs section. http://www.wayofthepixel.net/pixelation/index.php

# Answer
> 0 votes
Try the game maker community, gmc.yoyogames.com

They have quite a few good pixel artists there, quite a few who also will animate. The downfall is that you have to be very selective about who you pay, because the range of people who say they are "good" ranges all the way down to 8 year old noobs.

However one major benefit, is that for individual pieces of art, you can tend to post a request and get half a dozen to choose from, and payment is very rarely required.

---
Tags: sprites, hiring
---


title: How do you create a fractal cube-map?

text:
# Question
Title: How do you create a fractal cube-map?
I want to create a map similar to how Mincraft and other related games do. I just haven't the faintest clue on how to do so. Can anyone point me to a decent tutorial or give me a decent run through? I program in java and use openGL.

# Answer
Are you looking for something like this?

Voxel heightmap terrain editor

The article I mention in that answer is pretty good and talks about creating maps exactly like Minecraft. Using that article as a starter I was able to create maps like this for my game.
> 4 votes

---
Tags: opengl, java, cubemap
---


# Question
Title: Best way to traverse triangles in a mesh
I'm implementing non-projective decals. As described in many places (ie: lengyel in the gpg2) I first need to detect all triangles that lie within some sort of frustum.

Besides obvious brute-force solutions (ie: checking each triangle), what are better ways to generally search triangles in a mesh? One solution i can think of is, for each mesh, keep some parallel data structure better suited for searching. are there any well know algo/solutions?

# Answer
> 0 votes
I agree that frustum culling type algorithms are the way to go. Although, I would just use an Octree or KD-Tree, and hierarchically test for an intersection using that. Unless you expect high depth complexity and a poor rendering order, I would skip a technique that does occlusion computation to save development time. It is possible to use multiple Oct/KD-tree hierarchies to support complex animated objects, or dynamic Oct/KD-trees of simple objects to prevent testing against each moving object.

# Answer
> 1 votes
Are you referring to frustum culling? There are many algorithms developed to speed up the process, but primarily, you aim to perform as little comparisons as possible per-object. So for instance, rather than checking that each triangle within an object lies within the viewing frustum, you can check the extremities (i.e. the left-most and right-most polygons), if these are both within the viewing frustum, no further check is necessary, the entire object is within the viewing frustum, if one of the extremities does not lie within the frustum, then check the middle polygon, and think of it as the same principle as binary sorting. As the polygons are ordered by position, you can get away with a lot fewer checks than ***O***\[n\].

Other techniques include that used by the Quake Engine (and by extension the Source engine), with their BSP mapping, this process involves sorting your map into VisLeafs (Visibility leaves), which allows the engine to determine when a player is at one point in the map, what it is impossible for him to see, and thus that is never rendered, even if it is technically within the viewing frustum. This is done by dividing up the space using a series of planes and storing the information within the .bsp itself.

I hope this answers your question, and I've not just digressed into something totally irrelevant to you, if I have then leave a comment and I'll try my best to ammend this answer. :)

---
Tags: collision-detection, algorithm, 3d-meshes, data-structure
---


# Question
Title: How to determine an irregular area of a CCSprite?
In my simple game I use boundingBox for pick coins and other stuff, but I need use irregular area detection of Sprite(with out Alpha)... There is alternative to boundingBox? Here is code:

```
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [touch locationInView:[touch view]];
CGPoint point = [[CCDirector sharedDirector] convertToGL:location];
curentPosition = point;
arrToDel = [[NSMutableArray alloc] initWithCapacity:0];

CCSprite *coin = nil;

for (Coins *coins in self.bugs) {
    if (CGRectContainsPoint([coins boundingBox], curentPosition)) {
        coin = coins; // found sprite
    }
}

if (coin != nil) {
    NSMutableArray *checkList = [NSMutableArray arrayWithCapacity:0];

    for (Coins *coins in self.bugs) {
        if (CGRectIntersectsRect([coin boundingBoxInPixels], [coins boundingBox]) && coins != coin) {
            [checkList addObject:coins];
        }
    }

    int max = coin.zOrder;

    for (Coins *b in checkList) {
        if (b.zOrder > max)
            max = b.zOrder;
    }

    if (max == coin.zOrder) {

        [self removeChild:coin cleanup:YES];

        [arrToDel addObject:coin];

        for (Coins *coins in  arrToDel) {

            [self.bugs removeObject:coin];

        }
    }
}

```

}

# Answer
> 1 votes
For this you may use CGPath. You can find answer on your question here

# Answer
> 2 votes
If your sprites can be decomposed into a series of bounding boxes or other easy-to-detect primitive shapes, you could use that collection of bounding boxes instead. That probably won't scale, however, -- a more common approach is to use collision masks. A mask is essentially a B&W version of the sprite where white means "not part of the sprite" and black means "part of the sprite."

If your source sprites have alpha or color key data, you can either use directly as the mask or use it produce the mask images programmatically. Otherwise you may need to author the mask images in a paint program.

Anyhow, once you have the mask you first do a simple bounding-box check to trivially reject collisions that aren't even close. Then you test against the mask image -- in this case it looks like you'd transform currentPosition into the local space of the mask image (subtract the current position from the origin of the bounding box) and then see if the pixel in the mask at the transformed index was black or white, and that will let you know if the user touched part of the sprite or not.

Note that you may also find that you'll need to enlarge the hit test area from a single pixel in order to make this feel good, especially on a real phone when you're using real fingers as the input instead of a mouse on the simulator.

# Answer
> 1 votes
If the sprite doesn't change, you could give it a convex bounding polygon. Computing collisions is more complicated than with rectangles, but not much more.

Even if it does change, computing an appropriate polygon at runtime is not terribly hard.

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


title: Incorrect angle calculation?

text:
# Question
Title: Incorrect angle calculation?
I'm trying to create a simple topdown game, in which you control the player by WASD keys and use mouse to aim and shoot. So far, I have a player moving and firing, but I think there is something wrong with the shooting.

Accuracy gets lower as the mouse cursor move away from the player.

Please try the following SWF to see more clearly what I'm trying to say.

http://dl.dropbox.com/u/24777511/gdstack.swf

Here is a chunk of relevant code:

```
private function fireBullet(x:Number, y:Number, dFireAngle:Number):void {
            var b:Bullet = recycleBullet();
            var rFireAngle:Number;
            b.reset(x, y);
            b.angle = dFireAngle;
            rFireAngle = (dFireAngle * (Math.PI / 180));

            b.velocity.x = Math.cos(rFireAngle) * 385;
            b.velocity.y = Math.sin(rFireAngle) * 385;
        }

```

...

```
if (FlxG.mouse.pressed()) {

                    var p:FlxPoint = new FlxPoint(FlxG.mouse.screenX, FlxG.mouse.screenY);
                    var angle:Number = FlxU.getAngle(new FlxPoint(player.x, player.y), p) - 90;
                    fireBullet(player.x, player.y, angle);
...

```

# Answer
I used the following code instead of Flixel's getAngle and strangely, it works:

```
var dx:Number = x2 - x1;
var dy:Number = y2 - y1;
return Math.atan2(dy,dx);

```
> 3 votes

# Answer
The Flixel code just calls `Math.atan2(Y,X) * 180 / Math.PI`, which looks ok. Have you checked that you're not accidentally rounding floats down to ints at any point in those calculations?
> 2 votes

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


title: Scene graphs vs in-game representation

text:
# Question
Title: Scene graphs vs in-game representation
This is a general question which aim is to allow me to start digging on the subject by myself.

As I noticed the general opinion is that scene graphs are good for describing the scene in a level editor (or any editor that the game is using), but the game itself should use some sort of optimized data structure internally and the scene graphs should be somehow "translated" to that data structure before use.

What such internal data structures would be? How one would "translate" a scene graph to such structures.

In general - the more detail you can give me then better. Also references/links are more than welcome. :)

# Answer
> 1 votes
So talking about this internal data structure, this can be a scenegraph too and a scene graph can be anything you want it to be. When you start with a game engine you can have an simple array which holds (object/position) pairs. So you can simple traverse this array and draw the objects on their respective position. When going further you can add rotation to that. Most engines will have a tree like scene graph which means that you can have a position/rotation relative to your parent. You can add anything you like to your scenegraph, but what is the most important is that start simple and add later. Once you grasp the basic concept you see that it is not so difficult.

For the optimizing part I would say, optimize when framerate drops. Maybe you will never get to that point. There are several options like frustum culling which you can do when adding spatial information to your scene graph. Like putting AABBs around your objects so you can test them against the frustum.

---
Tags: data-structure, scene-graph
---


# Question
Title: I would like to know how an OpenGL driver will be implemented to learn opengl internals?
I'm learning OpenGL and really like to know how the interaction with the Graphics card will be.

I feel understanding how it was implemented in the Graphics driver, will let me know complete internals of the opengl(With this I can know what stages/factors influence my decisions regarding performance in opengl).

Are there any ways for this path to proceed.Does exploring the 'Mesa lib' will help me in this aspect? Am I in the right path?

\[I posted this question in SOF but it seems here is the right place for this Question.\]

# Answer
You can start be reading this blog: http://fgiesen.wordpress.com/2011/07/09/a-trip-through-the-graphics-pipeline-2011-index/
> 7 votes

# Answer
Have a look at Mesa3D. It's an open source OpenGL implementation for GNU/Linux and many other OS's.
> 0 votes

# Answer
I think this site has some great information about the subject: http://www.songho.ca/opengl/gl\_pipeline.html
> 0 votes

---
Tags: opengl, architecture, graphics, gpu
---


title: C# vs Java for Cross-Platform Game Dev

text:
# Question
Title: C# vs Java for Cross-Platform Game Dev
What would be better for PC (Windows, Linux, Mac) games?

I know Java is more mature/older and has a giant user base, but I see C# (Mono) slowly rising and showing that it has a growing user base as well.

I've seen lots of games written in Java like Minecraft, Runescape etc. (Haven't really seen any popular C# games!)

But what would be better?

More Info(Ideas for games I'm going to make): 3D games (FPS, Racer, TPS?) and maybe 2D games (Platformer?)

# Answer
I personally prefer Java.

Because:

* Java have applets for web-based games (sliverlight is not already installed by default). Applets are very good for demos.
* Java is already installed on Mac OS and on most Linux distributions.
* You can run Java in mono or even compiling Java Code to x86 Code "http://www.mono-project.com/Java" and there is gcj also.
* More and more people started to use java for games because of android today has the biggest market share in the mobile OS market.
* I like to use Eclipse

This is just my point of view. Use whatever works best for you.

You can look at some compaction between java and c#:

http://www.javacamp.org/javavscsharp/
> 2 votes

---
Tags: c#, java, windows, linux, mono
---


# Question
Title: Is there a legal option for writing Nintendo 64 games?
Recently, I've been looking into developing games for Nintendo 64 emulators, and modding existing ROMs. I wanted to know if there is the *possibility* for any *legitimate* tools out there which can be used to write the code for the emulators or if all of that is off limits.

I heard that the Nintendo 64 SDK has always been sealed by an NDA limited to the game studios, years ago; however, I'm curious about where all the current ROMs that are available came from. Mainly because, unlike discs, cartridges are not typically supported by standard hardware.

# Answer
> 5 votes
> I'm curious about where all the current ROMs available came from (mainly because unlike discs, cartridges are not typically supported by standard hardware).

There are basically two kinds of ROMs -- images of commercial titles obtained through questionable legal means using cartridge dumping hardware, and images of homebrew titles that are written directly from your PCs memory to disk via the homebrew SDKs that are floating around. Most of the ROMs you are probably thinking of are the former kind. Cartridge dumpers are essentially hardware, sometimes custom-built, that copy the read-only memory chips on a cartridge to disk in some format.

> By any chance is there still a serious reason why the tools are still sealed?

There is no business advantage to Nintendo to make the tools available. They would turn no profit from it. Plus, especially for older consoles, many of the older official SDKs talk with proprietary hardware (dev kits) that may not even be in production any longer, so there's very little you could likely *do* with the toolchain from Nintendo.

Homebrew console SDKs produce ROMs because emulators already exist. It's unlikely that most official SDKs produced ROM images that could be consumed in exactly the same fashion.

---
Tags: legal, nintendo
---


title: optimal pixel-read back strategy

text:
# Question
Title: optimal pixel-read back strategy
I need to render certain scenes and read the whole image back in main memory for further processing which is not suitable for rewriting into shaders of CUDA, and saving to disk. I've search for this and it seems that most video cards will accelerate the rendering but the read-back will be very slow. After a bit of research i only found this card mentioning "Hardware-Accelerated Pixel Read-Back"

The other approach would do software rendering and the read-back problem doesn't exist, but then the rendering performance will be bad.

Likely, i will have to implement both in order to be able to find the optimal trade-off, but my question is about what other alternative can i have hardware-wise; i understand Quadro is for modelling and designer market segment, which is precisely the client target of this application, Does this means that i'm not likely to find better pixel read-back performance in other video card lines? i.e: Tesla or Fermi, which don't even have video outputs btw

# Answer
We're talking about relative performance here, it's not like suddenly your bitmap gets transferred at baudot speeds back to your main memory. Is it slower than a main RAM copy? Absolutely. Is it slower than software rendering? Absolutely NOT.

Do you need to do this at interactive speeds, 30-60Hz, or is a slower overall throughput an option? What bitmap sizes are you rendering, 4Kx4K will always be slow, 800x600 you could probably even do simple shaders in software at reasonable rates.

If you want comparisons on what's possible in the consumer space, Fraps has spent a lot of time doing compressed captures to disk from video memory http://www.fraps.com/ and if you're trying to get performance that exceeds their limits you're looking at some heavy R&D and probably hardware specific.
> 1 votes

---
Tags: performance, linux, hardware-acceleration, nvidia
---


# Question
Title: Where can I find some beginners to learn and work with?
I am very new to game programming. I am currently studying Java (Android mainly) and I know what it takes to make a game, as well as how to render it via OpenGL. Finding some others at nearly my level I think would motivate me more and give me some experience to working with others. Do you know a good place to find some people?

Thank you in advance!

# Answer
You might try looking at the GDNet Help Wanted forums and/or the TIGSource forums.
> 2 votes

# Answer
I like this forum http://www.java-gaming.org/
> 1 votes

---
Tags: java
---


# Question
Title: Best way to notify a user on Facebook that it's their turn to act
I'm creating a turn-based game that I'd like to integrate into Facebook. Players may not necessarily be playing in real time so having a way for them to know when it's their turn is desirable.

I was initially thinking facebook notifications, but it appears that has been deprecated: https://stackoverflow.com/questions/4619164/how-to-send-a-facebook-notification-through-their-api

The alternatives don't sound terribly pleasant (writing on their wall, or having the player that just finished their turn send a request)

Are there any better alternatives?

# Answer
> 6 votes
Requests were created for this purpose among others...

> App-generated requests: These requests can be initiated and sent only to users who have authorized your app. Developers can send these requests using the Graph API. Use these requests to update the bookmark count to encourage a user to re-engage in the app **(e.g., your friend finished her move in a game and it’s now your turn)**.

See: http://developers.facebook.com/blog/post/464/

# Answer
> 1 votes
Facebook doesn't allow applications to send direct messages. I think there is no way to generate a notification with an app on facebook, you can only write on the users wall.

Maybe your best solution is to send an SMS, email or use twitter.

---
Tags: facebook
---


# Question
Title: Multiplayer synchronization and pathfinding
I have a point & click type interface on a client, which runs an A\* on the server, for path-finding.

The game is controlled like an RTS, but the world is persistent, so players should be able to join/leave at any time, and there will only be 30 or so units at most on the screen.

What is the best way to synchronize the player movements between the server and client, once I've computed the path(s)?

Does the server need to sync the clients on every animation step/frame? or can it just tell the client "go to position X,Y" for each node on the path, and each moving player? Or is it best to just run the animation timers on both client and server, and have it be implicitly synchronized that way?

What would the typical data-exchange be like for path-based movement?

EDIT:

Some of you have been suggesting lockstep, because I said "RTS", but the game isn't an RTS, it just has the same kind of interface. The big difference is **I need to be able to have players join and leave the game at any time**. Sorry for not being more specific.

# Answer
> 2 votes
An alternative is to do pathfinding on the client that owns the unit. This has the advantage of spreading the work out more evenly. A disadvantage of doing all the pathfinding on the server is that the server has to do all of it; a disadvantage of sending only 'move to X,Y' commands to clients is that each client has to find every single path. Instead, every 'tick' in the lock-step cycle, each client tells the server, literally, each of their unit's next step. The server makes sure the unit actually can move there, and moves the unit. Since the client doesn't have all the information (Notably, what the other client's units are doing), an invalid movement command isn't treated as an error. This is giving up some bandwidth to gain more time for calculating paths.

Replace server with peer; this method works for a peer-to-peer games as well, so long as you make sure the order in which unit movements are considered is the same on all machines.

# Answer
> 1 votes
RTS games typically have lockstep-sync (sync happens every frame). Telling any paths to the client would allow hacked clients to abuse the extra information.

# Answer
> 1 votes
Neither. The only thing you should send are the commands. Example: These 20 units should move to (X,Y) and then let each player figure out how they get there. The tricky part is making sure they all do the exact same thing. To achieve this a lockstep model is used, the links below should explain it in detail. Also, you should only sync the important pieces. Anything that doesn't change the gameplay shouldn't get synced. Animations in RTS games is usually only for the visual side.

Another thing, RTS games are usually not client-server, but P2P. That way one of the players can't cheat because when any inconsistency is detected, you simply disconnect.

Here is something to help you get going: http://www.gamasutra.com/view/feature/3094/1500\_archers\_on\_a\_288\_network\_.php http://altdevblogaday.com/2011/07/09/synchronous-rts-engines-and-a-tale-of-desyncs/ http://altdevblogaday.com/2011/07/24/synchronous-rts-engines-2-sync-harder/

# Answer
> 1 votes
Once the path is calculated, the server just uses that path to control the character. The presence of a path makes no difference to this problem - you still just send the same data, whether that is regular position updates or whatever. Usually it's fine to send regular positions (interpolated on the client to smooth them) and a separate message when the unit stops.

# Answer
> 1 votes
In my game (a multiplayer RPG type game) I send parts of the path to the client (for NPC nearby), ie. the 3 next positions and the Time when the NPC should be there. For players I just send the latest valid position + its timestamp so that on the client I can do dead reckoning (or something more elaborate if wanted).

This works completely OK mostly because there are no collisions between players/NPC (with a low lag you don't really notice anything, with a, say 250+ msec lag you notice the difference if you can see the two screens (of two players) at the same time but it still is not really noteciable on 'one screen').

So I'd say: go with server authoring (validationg positions + timestamps of players and also for the AI in the beginning, you can make a more elaborated system for the NPC later on without any big problems) + client prediction.

ps. I use a millisecond precision which works perfectly OK except that a signed int only holds for some 3 weeks before I have to restart the server.

You might also want to check out time prediction (ie. trying to get in sync as closely as possible with the server).

---
Tags: animation, multiplayer, synchronization
---


# Question
Title: LWJGL glRotatef() without rotating axes?
Okay so, I noticed when you rotate around an axis, say you do this:

```
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);

```

That will rotate things 90 degrees around the x-axis. However, it also sort of rotates the y and z axes as well. So now the y-axis is pointing in and out of the screen, instead of up and down. So when I try to do stuff like this:

```
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glRotatef(whatever, 0.0f, 1.0f, 0.0f);
glRotatef(whatever2, 0.0f, 0.0f, 1.0f);

```

The rotations around the y and z-axes end up not how I want them. I was wondering if there is any way I can sort of rotate just the axes back to their initial position after using glRotatef(), without rotating the object back. Or something like that, just so that when I rotate around the y-axis, it rotates around a vertical axis.

EDIT: After further research, it appears I will have to learn quaternions. EDIT2: Wait, I don't think that's right. Does anyone know? I saw this thread on another site: http://java-gaming.org/index.php?topic=24177.0 but I don't understand what he did.

# Answer
> 3 votes
I personally don't care much for answers that are just links to other stuff, but these two tutorials explain matrices and transformations really well. They explain why it is that creating a Y-rotation matrix doesn't rotate about world-space Y, and the second link explains how to rotate things in different spaces, and how to overcome these kinds of issues.

Yes, the tutorials are for shader-based programming. But transformation matrices are the same, whether using shaders or fixed-function.

In the interest of full disclosure, I wrote these, so take the above for what it's worth.

# Answer
> 0 votes
Once your matrix is no longer aligned with the world axes, you have to apply the rotations about the local space axes, not the world space axes.

Doesn't OpenGl have a method for rotating around an arbitrary axis?

If so, store the basis vectors frome the previous matrix's rotation as the Local space axis vectors and use them as an arbitrary axes to rotate the matrix about during the next rotation.

# Answer
> -3 votes
You need to do the following.

Store the rotation around the x, y and z axis separately for each object (as floats).

Every frame:

* reset the rotation matrix (`glLoadIdentity();`)
* apply roll
* apply pitch
* apply yaw

If you do it in this order you should not have any problems. Just make sure you don't do 'repeated rotations' since then you get a lot of problems.

Edit: sorry I first had the wrong order here, I probably got confused because of left-hand / right-hand differences.

---
Tags: java, rotation, lwjgl
---


# Question
Title: Term for a game that used to cost money but is now a public license
What is the term for this:

> A game that used to cost money, but is so old that it is now available for free (though not always open-sourced).

# Answer
The term is 'Freeware' (if the game was officially released for free by the company late in it's life), or 'public domain' if the copyright ran out. Copyrights last too long in the US, and no game has hit the 'automatic' lapse of copyright.

There is also the term 'Abandonware', which usually means "the game/software is old and no longer being sold or supported". Many people think that abandonware can be distributed legally, but that is not true. Someone still owns the copyright on those games, though in many cases the exact owner is a mystery even to the owner.

Wikipedia has a list of freeware games: http://en.wikipedia.org/wiki/List\_of\_freeware\_video\_games
> 3 votes

# Answer
Unless what you're wanting to do falls under copyright, trademarks, or patents, you're free to do whatever. Generally speaking, *mechanics* aren't protected. Names are. Art is (and that includes things like music and level design). You can make a "clone" in the sense that it's a very similar game, but you can't call your Tetris clone "Tris" and not expect some lawyers to get involved. Likewise I wouldn't make a pacman clone with the same board layout and look of the characters. But you could probably do something with nearly identical mechanics and a different skin.
> 2 votes

# Answer
The **terminology** you're asking about is **"abandonware"** (which is a combination of elements from the words "abandoned" and "software"), but free doesn't necessarily mean the copyright holder permitted it to be free.

A note about downloads: There are a few vendors who are known for allowing the old copies to be distributed freely (and I'm not aware of any that are \[intentionally\] open source), but as far as I know this is so rare that you might as well assume that any abandoned game you can download likely involves a copyright violation even if the company has gone out of business (you'll need to consult legal expertise to find out how copyright works in your jurisdiction with regard to a particular title).
> 0 votes

---
Tags: terminology, licensing
---


# Question
Title: How should I implement multi-pass rendering in a game engine?
I have done multi-pass rendering, before, and understand how it works. I made a simple example, which rendered a basic scene with shadows. This was all part of one file. Now, I am trying to figure out is how to put it into my game engine.

Currently, my game engine uses a single pass. It is in a hierarchical structure, and uses Direct3D 9. I have a graphics component, which will load and draw a 3D model. In my game loop, I update all of the entities in the world, then I call the draw function for each one. This draw function gets the vertex buffer, index buffer and texture or material, and draws the 3D model using a shader. This works fine.

To do multi-pass rendering, to allow for shadows, I will need to draw each model multiple times. It doesn't seem right, to me, that in each models draw function I should put the second pass code; this will then be completed before the next models first pass.

How should I implement multi-pass rendering in a game engine?

# Answer
The entities should not be responsible for drawing themselves. They (or just their renderable components) should be passed to the rendering engine and the rendering engine should have the responsibility of rendering them.
> 7 votes

# Answer
With your current structure you'll need a second API for your models to handle the shadow pass.

If you wanted to invert some of your logic then let the models store their data and a friendly description of how they want to be rendered, and let the graphics engine pull data from the models to render according to those descriptions. This will let the graphics code handle the shadows (or post processing FX, etc...) in its own way with the second pass.
> 0 votes

---
Tags: shaders, directx, rendering
---


title: How to build Ogre3d with boost?

text:
# Question
Title: How to build Ogre3d with boost?
I have a simple question.

For people that know and built ogre3D from source as a Static library, what is the order of which the libraries should be linked?

The libraries I need to be organized are:

* Ogre Plugins
* 'libOgreMain.a'
* Ogre RenderSystems
* Boost(version 1.47)link
* Ogre's Dependencies

The reason I'm asking is because in the Ogre forums, I have asked about this and didn't get a good reply... yet.

The other reason is because even though I link to the boost library, I get this error:

```
undefined reference to '_imp___ZN5boost6thread20hardware_concurrencyEv'

```

My compiler is MinGW with CodeBlocks as the IDE.

And my main computer I'm building on is Windows Vista 32 bit.

# Answer
> 1 votes
I didn't know that there were link order dependencies in Ogre's basic SDK build, I certainly never had to rearrange anything on the Windows platform. Are you sure that you're using the right version of Boost?

Another thought, if you're using plugins it's possible that one of them is out of date and needs updating to a matching Boost with a recompile.

Try the compiler option -DBOOST\_THREAD\_USE\_LIB

---
Tags: c++, ogre
---


# Question
Title: How to include fur in the exported obj file in Maya?
In Maya I use fur to create plants. In my game I want to render these plants with cel shading. I use Wavefront .obj as a file format in my game for the models, but it doesn't seem to include the fur.

Is there a way to export the fur (as vertices) with the model into the obj file? Generating the fur at runtime is a bit CPU expensive for the platform.

# Answer
> 3 votes
Fur is usually implemented as a render effect -- there isn't a 1:1 correspondence with geometry, although geometry may be used to achieve the effect (textured polygonal strips, for example, or the newer and better looking 'shells and fins' methods), so there isn't really anything to export unless you were you convert the fur representation to 3D geometry. *This would almost certainly result in extremely poor performance in your game.*

The solution you probably want to is abandon using Maya to generate the foliage and employ a rendering effect in your game code to achieve the desired results instead. The article I linked to before provides one possible implementation; here is another example, using XNA.

However, since you said you are using Maya's fur rendering to produce plants, you may instead want to consider rendering algorithms designed for exactly that effect. Game Rendering has a whole section on "vegetation." There's quite a few options for grass rendering, for example:

I know you mentioned being CPU limited, but you didn't specify exactly how much so, or what the GPU resources you have available are. It should be reasonable these days to implement some level of these techniques with reasonable scalability back to older hardware and without too much CPU strain.

If that fails, you can always fall back to using simple polygonal billboard strips and "exporting" your fur out of Maya by rendering it as a texture you eventually apply to the billboards in your game. But actually exporting the fur as geometry is almost certainly not the approach you want.

---
Tags: models, maya, obj
---


# Question
Title: What's the difference between creating a Source mod and just creating some levels?
I'm just starting to look into creating Source mods for HL2 and I'm a little bit confused. I've gone through some tutorials on level creating to get the basics and it seems to me that it's all that really goes into the creation of a mod. I know I'm wrong so could someone please explain to me where the programming comes in? Is it more than just sticking NPCs and objects on a map?

# Answer
> 3 votes
You can create levels -- place existing objects in them and specify their behavioral parameters to an extent -- without programming. Programming in mods generally comes in to play when you want to modify or tweak the intrinsic behavior of things in the game, or create entirely new kinds of things with unique AI or effects, beyond what is possible by the stock engine and object library.

For Source specifically this tends to include things like entity behavior and AI, networking, rendering effects, and UI.

---
Tags: modding
---


title: Some questions about lists

text:
# Question
Title: Some questions about lists
I've been looking for articles or tutorials on this and I can't seem to find any, so I thought I'd ask here. I've created a bullet class in my game that is added and removed through a list. If I'm going to make these bullets work the way I want them to I need to be able to do two things:

One, I need to check if the bullets are colliding with each other and then remove the two bullets that are colliding. I've tried doing it by updating the bullet list with a for statement and then checking for collision with another for statement, but that occasionally crashes the game.

Two, I need to be able to check how far away every other bullet in the list is from the current one.

So how can I go about doing this?

# Answer
The crash you are getting is probably because you are removing objects from the list while iterating through it. This will modify the `Count` of the list and the iterator will try to access elements that no longer exist.

The solution is to use a second list to which you add the objects that must be deleted.

```
for(int i = 0; i < bulletList.Count - 1; i++)
{
    for(int j = i + 1; j < bulletList.Count; j++)
    {
        if(bulletList[i].CollidesWith(bulletList[j])
        {
            bulletsColliding.Add(bulletList[i]);
            bulletsColliding.Add(bulletList[j]);
        }
    }
}

for(int i = 0; i < bulletsColliding.Count; i++)
{
    bulletList.Remove(bulletsColliding[i]);
}
bulletsColliding.Clear();

```

Unfortunately, the problem with this is that you can get duplicates of bullets in your bullets colliding list if a bullet is colliding with more than one bullet at a time. Using C# lists the `Remove` function will only return false though.

Using flags to set the bullets to `Alive` or not can be a good idea to stop you from having to instanciate a Bullet if dead ones aleady exist. I would however just 'move' the bullets into a second list which is neither `Draw()`'n nor `Update()`'d, and move them back when you need to create a new bullet, and the list isn't empty.

You must be very careful though that the Bullet instance is properly reset before you re-insert it into the working list.

---

To check the distance between bullets, you can use Pythagoras' theorem. In 2D :

```
float Distance(Bullet a, Bullet b)
{
    float xDistance = b.x - a.x;
    float yDistance = b.y - a.y;

    float sqDistance = (xDistance * xDistance) + (yDistance * yDistance);

    return Math.sqrt(sqDistance);
}

```

In very time-critical sections, it is common to use squared positions of objects and not perform the square-root operation, as it is quite expensive.
> 6 votes

# Answer
I would use an array of Bullets (with Bullet value type), with an "Alive" flag to "add/remove" bullets without generating too much garbage. You can iterate over the array and simply skip bullets that are not currently used (make sure to clear data before deactivating them).

The first point is tricky. If you check every bullet against all other bullets and repeat, you're going to have way too many checks. You could have a spatial partitioning system and move from there.

Is it a "bullet hell"-type of game?
> 0 votes

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


# Question
Title: How can I get textures on edge of walls like in Super Metroid and Aquaria?
Games like Super Metroid and Aquaria present the terrain with the other facing parts having rocks and stuff while deeper behind them (i.e. underground) there's different detail or just black.

I would like to do something similar using polygons. Terrain is created in my current level as a set of overlapping square boxes. I'm not sure if this rendering method will work such a system for creating terrain but if anyone has ideas I'd love to hear them. Otherwise I'd like to know how I should re-write the terrain rendering system so it actually works to draw terrain in this manner...

# Answer
Metroid's just using tiles, nothing special going on there.

Aquaria however is doing something rather clever. If you'll notice, a lot of those rocks on the bed get repeated several times. Here's one of the rocks for instance:

It looks like they've just dumped sprites along the edges of their terrain. It's kind of like what Metroid did - a massive arsenal of edge tiles, but if you pay attention you can notice the repetition of the tiles. Acquaria's doing the same thing, except with rock sprites, and not on a grid.

# How to replicate it

This might not be exactly how they do it, but it's one way of producing the same end result.

First, get yourself a nice bunch of rock sprites like this:

Now there's a process to follow so you know where to put them.

# Tada!

You can use this *once* to generate a list of rocks and where to draw them, then you just draw all your rock sprites. Or maybe you can just draw all the points and pick a different sprite to draw on it on each step, making the edge of a lava pit or an alien terrain!

# And other terrain features...

Aquaria could've used a very similar method to dump all the mushrooms, coral and other features on the seabed (including the giant rocky structures that form the backdrop). The mushrooms could have been generated like this:

1. Gather some points at *random* intervals, not fixed intervals.
2. Don't just store the point. Also store the *normal* of the edge you picked the point from.
3. Pick a random rotation within a certain range of the normal's rotation. For example if the normal is pointing off at 30 degrees, pick a rotation within 20 degrees of that (i.e. between 10-50 degrees).
4. Draw your mushroom at the chosen rotation, and at a random stalk length.

Everything else is probably a variation on those same instructions: the coral isn't rotated much, those two shells/stones are probably only placed if the terrain normal is pointing roughly upwards (i.e. the terrain's flat).

### Final Notes

Since a commenter asked: I create these images in Adobe Photoshop (shrunk on here by 50% for crisp lines) using a Wacom Intuos3 tablet (which lets me draw freehand and naturally, and vary my line width etc).
> 131 votes

# Answer
Doing this with Polygons would be quite simple, so long as you have a nice repeating/tiling pattern, you can easily set your models to duplicate along a curve, nothing complex at all.

Hope that helps.
> 3 votes

---
Tags: 2d, rendering, software-engineering
---


title: What language for Indie dev?

text:
# Question
Title: What language for Indie dev?
What would be a easy/fast language that would be good for an Indie developer for a FPS?

Java? C#? C++? C? Anything else that would be good?

Edit: (Platforms: Linux, Mac, Windows)

# Answer
> 6 votes
The one you know better, and that works on the platform you want to build games on.

# Answer
> 1 votes
If you wan't to minimize the amount of code to ship your game on the 3 platforms, I guess you should use a standard like C++ or Java.

The advantage of C++ is that it is more fast at runtime, but you need to recompile your project for each platform, and sometimes use different libraries for OS specific features. Also you can control more easily how to handle your memory.

The advantage of Java is that it's generic, and if you don't know pointer arithmetic, easier to write.

I guess there are other solutions, like Flash, but these are the best solutions in my opinion.

# Answer
> 0 votes
Go for the easy ones like C# or Java because you need it fast and you don't seem to mind which language to choose.

I think Java might be a good choice as it can run on all 3 platforms, and there is a good 3D engine JMonkeyEngine. C# would go with the XNA framework I think, but it's restricted to Windows only and not as high-level as the JMonkeyEngine.

---
Tags: game-design, software-engineering
---


# Question
Title: I want to get rid of my make-everything-static-and-global design pattern, but how?
I'm making a little dungeon crawler in space, and I'd like to hear some advice on how to make the backend of the engine nicer. Basically, currently everything is based on a crapload of managers:

* BackgroundManager: has `AddBackground(image, parallax)` method for making cool background effects.
* ConfigManager: reads/makes the config file and also holds the data read from that config file.
* DrawManager: has `Draw(sprite)` method to draw stuff to the screen, and things like `SetView(view)`, `GetView()` etc.
* EntityManager: holds all active entities and has methods for adding, removing and finding entities.
* DungeonManager (actually called a GridManager, but this is for simplicity): has methods like `GenerateDungeon()`, `PlaceEnemies()`, `PlaceFinish()` etc.

Now I'm not even halfway there listing all my managers, so I think this has got to change. My game is also based on Screens, which makes it more annoying because I don't need half of the stuff my managers are managing in, for example, the main menu (I don't need physics/entities/dungeons in my main menu!)

Now I thought about making the managers not static, and giving my ScreenMainGame an instance of all game-specific managers. But that makes calling/getting anything related to the managers a huge mess... for example, if I wanted to draw my dungeon from any place that's not in `ScreenMainGame.Draw()`, I'd have to do this...

```
((ScreenMainGame)ScreenManager.CurrentScreen).GridManager.Draw()

```

That's really ugly.

So, fellow game developers, does any of you have an idea how to solve this mess? I'd be appreciated!

# Answer
> 10 votes
What about a component-based engine?

You would have a main class named `Engine`, which would keep a list of `GameScreens`, which would themselves hold a list of `Components`.

The engine has an `Update` and a `Draw` method and both call the `GameScreen`'s `Update` and `Draw` methods, which themselves go through every component and call `Update` and `Draw`.

Presented like that, I agree that it sounds like a poor and repetitive design. But believe me, my code became much cleaner by using a component-based approach than it did with all my old *manager* classes.

It's much simpler to maintain such code too, since you're just going through a big class hierarchy and not having to search through `BackgroundManager` for all the specific different backgrounds. You just have a `ScrollingBackground`, `ParallaxBackground`, `StaticBackground`, etc. which all derive from a `Background` class.

You'll eventually build up a pretty solid engine that you can reuse over all your projects with a lot of frequently used components and helper methods (e.g. a `FrameRateDisplayer` as a debugging utility, a `Sprite` class as a basic sprite with a texture and extension methods for vectors and random number generation).

You would no longer have a `BackgroundManager` class, but a `Background` class which would manage itself instead.

When your game starts, all you have to do is this basically:

```
// when declaring variables:
Engine engine;

// when initializing:
engine = new Engine();
engine.Initialize();
engine.LoadContent();
engine.AddGameScreen(new MainMenuScreen());

// when updating:
engine.Update();

// when drawing:
engine.Draw();

```

And that's it for your game start code.

Then, for the main menu screen:

```
class MainMenuScreen : MenuScreen // where MenuScreen derives from the GameScreen class
{
    const int ENEMY_COUNT = 10;

    StaticBackground background;
    Player player;
    List<Enemy> enemies;

    public override void Initialize()
    {
        background = new StaticBackground();
        player = new Player();
        enemies = new List<Enemy>();

        base.AddComponent(background); // defined within the GameScreen class
        base.AddComponent(player);
        for (int i = 0; i < ENEMY_COUNT; ++i)
        {
            Enemy newEnemy = new Enemy();
            enemies.Add(newEnemy);
            base.AddComponent(newEnemy);
        }
    }
}

```

You get the general idea.

You would also keep the reference of the `Engine` within all your `GameScreen` classes, to be able to add new screens even within a `GameScreen` class (e.g. when the user clicks on the *StartGame* button while within your `MainMenuScreen`, you can transition to the `GameplayScreen`).

The same goes for the `Component` class: it should hold the reference of its parent `GameScreen`, to have both access to the `Engine` class and its parent `GameScreen` to add new components (e.g. you can make a HUD-related class called `DrawableButton` which holds a `DrawableText` component and a `StaticBackground` component).

You can even apply other design patterns after that, like the "service design pattern"(not sure about the exact name) where you can keep different useful services within your `Engine` class(you simply keep a list of `IService`s and let other classes add services themselves). e.g. I would keep a `Camera2D` component over all my project as a service to apply its transformation when drawing other components. This avoids having to pass it as a parameter everywhere.

In conclusion, there certainly may be other better designs for an engine, but I found the engine proposed by this link very elegant, extremely easily maintainable and reusable. I would personally recommend at least trying it.

# Answer
> 1 votes
What you want to do is separate your code into components and services. XNA has built-in support for these already.

See this article on `GameComponents` and services. Then see this answer on using services in XNA, and this more general answer on services in any language.

# Answer
> -3 votes
Just because they are static or global doesn't mean they have to always be loaded/initialized. Use a Singleton pattern and allow the managers to be freeable and loaded again on demand.

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


# Question
Title: Using Actionscript 3's Graphics API in Flixel
My question sounds pretty simple but awfully, I couldn't find much information on the internet.

How can I draw a circle in my FlxSprite?

I couldn't find much information about drawing geometric objects or the usage of classic graphics API in Flixel.

# Answer
You can access the underlying BitmapData of a FlxSprite by using sprite.pixels or sprite.framePixels. You can then use BitmapData's drawing methods for simple things. If you need to draw a circle, you'll probably want to make a DisplayObject like a proper Sprite, draw on it using Graphics, and then use the BitmapData's draw() function to draw it onto the FlxSprite.

Note that this goes against Flixel's intended paradigm. If you're doing this once at the start of the game, or very rarely, it will work just fine to generate sprites procedurally. However, doing this every frame (e.g. in the render() code) will make probably make Flixel much slower. If you know ahead of time what sort of circle you need, you might want to just load the circle as a sprite from a file.
> 7 votes

---
Tags: actionscript-3, geometry, flixel
---


title: Gathering Stats from a StarCraft 2 game

text:
# Question
Title: Gathering Stats from a StarCraft 2 game
One of the maps I've played, nicknamed SotiS (DoTA in SC2) has the ability to maintain stats, which are sent back to their own server.

Does anybody know how this is done?

# Answer
> 6 votes
SC2 maps do not have the ability to connect to databases or web services - this could easily be abused. SoTiS can do it using a separate application, but most maps do not use this.

The only persistent storage SC2 maps have are the bank files, XML files saved with the extension `.SC2Bank` in your SC2 data folder. *All* player stats, settings, etc. from that map are stored in that map's bank file.

The maps usually do not actually keep track of global records - rather, they keep track locally of the best records seen so far. Every time a game is started, everyone's individual leaderboards are combined and overwritten with the combined leaderboard. This causes the leaderboard records to spread very quickly, much like a computer virus.

For example, if my top-3-players list consists of having seen player A with score 300, player B with 200, and C with 100; and you've seen player D with 400, A with 350 (he improved his score!) and E with 50; then when we play with each other, both of our high-score lists will be overwritten with player D with 400, A with 350, and B with 200. There are a few more kinks to work through (ex. usernames are not unique, so you also need to propagate some sort of unique ID), but otherwise this solution works well.

Of course, since the high-scores are stored locally, it will always be possible for someone to hack the scores. The only reason stats-hacking is not more widespread than it currently is is that the bank signature algorithm has not been reverse-engineered
**The bank signing algorithm has now been released to the public by hackers, and, as expected, high score lists on all maps are now completely meaningless.**

# Answer
> 2 votes
I believe you can write to files with the scripting available in SC2. The server interaction is done by a separate application.

---
Tags: starcraft-2
---


title: Learning Java for game development

text:
# Question
Title: Learning Java for game development
I am a systems administrator and for many years I worked with \*nix servers. My main experience programming is with Perl and shell scripting, but in my new job I've been told to learn Java and well... I'm not even interested in it. But what I am interested in is in game development, so while I don't have any interest in Java, I was wondering if I could use it to develop games?

I was wondering whether this is viable and if so, what approach should I take?

# Answer
> 7 votes
I think java proved itself as quite a viable programming language for programming games the same way that C# did with libraries such as *XNA*. It may not be as efficient as a low-level language like C++ in some situations because it is managed but it doesn't change the fact that it removes the need to manage memory by yourself (but then you have to deal with the garbage collector though).

Some successful java games: Minecraft, Runescape, other java games

Things java might be missing for game development.

I guess you could start out learning with this link and move on with other online tutorials after that.

Even though java can do the job, I'd still recommend trying out C# with XNA. C#'s syntax is, in a way, similar to java and won't take too much time to learn (if you know java).

Here are some resources for learning XNA and let me add this link that I recently discovered that is simply fantastic too.

But, hey, if you like java, program in java! Just program games in the language you prefer. Don't worry too much about how "efficient" or "viable" a language is until you feel like you master the game development's concepts enough to chose a language to use it at its full potential.

Just my little 2 cents on the subject.

Happy coding!

# Answer
> 3 votes
Java can definitely be used to develop games, and there have been some very successful games developed in Java. I think Jesse has already done a good job of giving some examples of desktop game development in Java, but I wanted to point out that you can also write mobile games for Android in Java. Don't expect to make much money on it, but the mobile space is very hot right now, and it's a great place to get some exposure for your work.

Additionally, check out the Java4K site for some other small projects written in Java. All of the games on the site use 4,096 bytes of memory or less in their compiled and packaged forms, including all art assets.

The one concern I'd have about writing a game in Java is that, while you get the convenience of automatic portability between PC operating systems, you'd have to completely rewrite your game if you wanted to port it to a platform like iOS. If you wrote it in C or C++, you'd have a bit more work to make it portable in the first place, but there would be no limit to the number of platforms you could port it to. But for a starting game developer, that's a minor concern. You should focus on just making some games before you worry about portability.

---
Tags: java
---


# Question
Title: I cannot update a shader constant via a constant buffer in DirectX 11
I've tried everything I can think of, but I cannot get a constant buffer to update a variable in my shader in DirectX 11. I followed the examples on msdn. I read and re-read the articles on constant buffers. I even followed the nearly identical thread on this site. But for some reason I simply cannot get this to work. Can someone point me in the right direction?

Here's the relevant code:

```
//my data variable to keep everything together
struct VS_CONSTANT_BUFFER
{
    D3DXMATRIX mWorldViewProj;
    D3DXVECTOR4 vSomeVectorThatMayBeNeededByASpecificShader;
    float fSomeFloatThatMayBeNeededByASpecificShader;
    float fTime;
    float fSomeFloatThatMayBeNeededByASpecificShader2;
    float fSomeFloatThatMayBeNeededByASpecificShader3;
};
    //I initialize my data variable
    D3DXMATRIX identity;
D3DXMatrixIdentity( &identity );
m_ConstantBufferContents.mWorldViewProj = identity;
m_ConstantBufferContents.vSomeVectorThatMayBeNeededByASpecificShader = D3DXVECTOR4(1,2,3,4);
m_ConstantBufferContents.fSomeFloatThatMayBeNeededByASpecificShader = 3.0f;
m_ConstantBufferContents.fTime = 1.0f;
m_ConstantBufferContents.fSomeFloatThatMayBeNeededByASpecificShader2 = 2.0f;
m_ConstantBufferContents.fSomeFloatThatMayBeNeededByASpecificShader3 = 4.0f;

// Fill in a buffer description.
D3D11_BUFFER_DESC cbDesc;
cbDesc.ByteWidth = sizeof( VS_CONSTANT_BUFFER );
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbDesc.MiscFlags = 0;
cbDesc.StructureByteStride = 0;

// Fill in the subresource data.
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = &m_ConstantBufferContents;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;

// Create the buffer.
HRESULT hr = pDevice->CreateBuffer( &cbDesc, &InitData, &m_ConstantBuffer );

    //from my update function, I update the contents of my buffer like so

m_ConstantBufferContents.mWorldViewProj = view;
// Set the buffer.
pDeviceContext->UpdateSubresource( m_ConstantBuffer, 0, 0, &m_ConstantBufferContents, 0, 0 );
pDeviceContext->VSSetConstantBuffers( 0, 1, &m_ConstantBuffer );

    //And this is how I attempt to use it in my shader
    //--------------------------------------------------------------------------------------
    // Constant Buffers
    //--------------------------------------------------------------------------------------
    cbuffer cbPerObject : register( b0 )
    {
       matrix  g_mWorldViewProjection  : packoffset( c0 );
       matrix  g_mWorld                : packoffset( c4 );
       float4  g_MaterialAmbientColor  : packoffset( c8 );
       float4  g_MaterialDiffuseColor  : packoffset( c9 );
    }

```

I'm sure it's something simple and stupid that I've overlooked, but I cannot seem to find the problem myself. Any ideas?

* Goishin

# Answer
Why have you defined your cbuffer as reading in from register `b0`? That might be a potential cause of your problem (the device context is writing to a different register than the one your buffer is reading in from).

Also, before writing to your buffer, you should use the `ID3D11DeviceContext::Map()` function, as you need to prevent the GPU reading from it before you are ready to pass it. Try the following:

Instead of this:

```
m_ConstantBufferContents.mWorldViewProj = view;

```

Try:

```
D3D11_MAPPED_SUBRESOURCE mappedResource;
pDeviceContext->Map( &m_ConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource )

VS_CONSTANT_BUFFER* dataPtr = (VS_CONSTANT_BUFFER*)mappedResource.pData;

dataPtr->mWorldViewProj = view;

pDeviceContext->Unmap( m_ConstantBuffer, 0 );

```

I think that's the correct syntax (been away from DirectX for a while, gradually easing myself back into it :P), but the concept is to ensure that it doesn't read the information before you've written the new information to it. That also might be causing your issue. I also don't believe that you need to tell the shader the offsets of the elements within the buffer, that should be figured out when you bring in your shader for compilation.

Other than that I don't see any issues that could be causing your problem. But then, I'm currently an "untrained eye", so to speak, so if you still can't get it to work, then try looking at the tutorials from this guy's website, they seem to be fairly good, and provide a good starting ground to build off of (I find once I have a working concept down, building on top of it is much easier, and enjoyable).

Hope this helps! :)
> 5 votes

---
Tags: shaders, directx11
---


title: Video playback in Unity

text:
# Question
Title: Video playback in Unity
I'm not satisfied with the quality of video playback in Unity (Movie texture which I run after converting video with Miro converter and importing it to Unity),... so, is there any chance that there is a 3rd party library which I can integrate inside Unity to play my movie file? My movie is full HD intro movie to my 3d app which can be played from application menu.

I've tried to use Media Player Classic (MPC) as external application, but the problem is, when I run MPC as new Process from application menu, my menu minimizes and this looks awkward for one stand alone app. When intro finishes, I have to maximize my menu by clicking on application icon placed on Windows taskbar.

# Answer
Unfortunately I don't know what level of freedom you have in selecting external libraries for use in Unity projects, but you might want to look at either:

Both of these options may very well be impractical due to the level of control Unity may give you over the lower-level OS objects -- window handles, primarily, and hooks for periodic updates.

Even if you got either of the above options to work, you'd be sacrificing portability (if that matters).

Based on some of the questions floating around Unity Answers (this one and this one, for example) it looks like video playback is not in an ideal state and may not get there any time soon.

Finally, you may want to browse some of the resources linked in this external Unity resources question, which might lead you to something useful for your purposes.
> 3 votes

# Answer
There is a C# wrapper for the well-known and open-source FFmpeg: http://www.ffmpeg-csharp.com/
> 2 votes

---
Tags: unity
---


# Question
Title: How does an Engine like Source process entities?
On the Source engine (and it's antecessor, goldsrc, quake's) the game objects are divided in two types, world and entities. The world is the map geometry and the entities are players, particles, sounds, scores, etc (for the Source Engine).

Every entity has a think function, which do all the logic for that entity.

So, if everything that needs to be processed comes from a base class with the think function, the game engine could store everything on a list and, on every frame, loop through it and call that function.

On a first look, this idea is reasonable, but it can take too much resources, if the game has a lot of entities..

So, how does a engine like Source take care (process, update, draw, etc) of the game objects?

# Answer
Well, there's pretty much no other way to do it - you're going to *have* to loop through and call `think()` for every entity at least once every few frames.

You could put entities on their own thread, but then you have the whole state-synchronization nightmare, which is definitely not worth it.

> On a first look, this idea is reasonable, but it can take too much resources, if the game has a lot of entities..

That is why the Source engine puts a hard limit to the number of entities which can exist at one time: 4096 entities, of which only half (2048) can be networked. Go over either of these limits, and the game will crash.

That is also why, when creating a map, they recommend you don't use more than about 800 entities.
> 5 votes

# Answer
These steps You mention are most likely done in separate engines. It is just that simple game engines usually have them in one pass. Your sequence

```
for each object
    do physics
    do game logic
    draw

```

becomes

```
call physics subsystem
call game logic subsystem
call drawing subsystem

```

Physics Engine takes care of positions and sizes.

Game Logic Engine takes care of interpreting what Physics Engine changed (he could obstruct some waypoints ...), what goals characters have and what behaviour they should be doing, he runs scheduled scripts (this **think** function).

Drawing Engine draws what objects are visible, and he knows what objects are visible because Quake engines kind of cheat here (see Draw section).

My advice to You is to rather study how simulations are done rather that game engines. There is a huge pop-culture relating game development and game engines are made in imperative languages (because of tradition&speed); so it was more enlightening to me to get good textbooks (rather theory) and THEN look at engines (practice) rather than look at engines and puzzle for hours how they did it.

# Physics

Whole notion of iterate all entities and do {think, draw} will probably lead to problems. There will be conflicts and so on. I belive Valve have Havok and I guess Havok takes care of enough-correct physics.

# Think

**Think** function is run when a time in a game equals time in **nextthink**. It works this way in Quake engine, and Quake engine is basis for Half Life engines. It is NOT run every time.

Internally it should be a simple iterating through a list of entities and checking if time has passed to call think function. Time complexity will be O(N), where N is number of entities.

If there is a very large number of entities You should measure how much it will improve the fps. Note, that because of Amdahl's law it is potentially invisible speedup. I mean, You just iterate trough all items and decrease&check one number.

I would speed it up by sorting entities by nextthink (create list of pointers to entities and sort it each time; not array of entities, because entities might change their nextthink anytime, so rearanging them in array takes O(N) instead of O(1) in list).

You should also look at O(1) scheduler in Linux.

# Draw

Engine draws what is approximately visible from area at which is camera. Game level is partition into a tree, and a area is leaf of that tree. I won't bother You with details about it... So if an entity is visible it is put into a set of visible entities and they are drawn.

They store what areas are potentially visible areas. It is called "potentialy visible set", PVS for short. There is visualisation of PVS, green capsule is player and around him is rendered what his PVS contains.
> 3 votes

# Answer
> So, if everything that needs to be processed comes from a base class with the think function, the game engine could store everything on a list and, on every frame, loop through it and call that function.
>
> On a first look, this idea is reasonable, but it can take too much resources, if the game has a lot of entities..

Actually putting everything in one big list is usually less than desirable; if you were to group the entities in lists based on, for example, their type, you could better distribute the processing over multiple threads. For example if you know all entities of type Foo never interact with any other entities during the simulation phase, you can offload them entirely. If they were scattered willy-nilly throughout some big singular list this would be much harder to do.

You don't necessarily even need to be deriving everything from a common base class at that point; Source goes fairly overboard with inheritance abuse for what could otherwise be implemented as data in that respect.

You will of course always have an upper limit on the number of entities you can process per frame, even if you start offloading work to other cores. There's no way around that, you just need to have an idea of what that limit is in your implementation and takes steps to alleviate it (proper culling of processing phases on objects that won't need them, avoiding over-granularity in objects, et cetera).
> 2 votes

# Answer
What you have to take into account and this following the train of thought of previous answers is that your performance will also be on when and how you call these think functions.

Looking at the link you posted on the source engine you can also read that you can setup think times and different think contexts for each of your entities, besides the obvious hard limit that someone already pointed out, this will be the key to achieving greater performance with a higher number of entities, either by creating stepped updates that spread performance hungry processing through multiple frames of execution, or by culling out un-needed processing depending on the current context ( i.e. entities that are too far away or beyond player perception dont need the same level of "think detail" as characters that are close a player simply wont see a character 2 miles away picking his nose ).

And there are other more specific levels of optimization depending on your specific game logic and situation.
> 1 votes

---
Tags: entity-system, design-patterns, logic, source-engine
---


title: How does Half Life's covering work?

text:
# Question
Title: How does Half Life's covering work?
Enemies in this game take cover. AFAIK HL uses some logical decisions for enemy to start searching for cover and to abandon cover, and I am able so far to find them; but how does he find a cover place?

I know HL has waypoints. I can only guess/speculate how they find cover point. They might search for nearest waypoint which has certain properties; I thought such node might have some "cover" tag but tutorials seem not to mention it; so maybe it is a node which is not visible by player AND offers attack possibility (crate or edge of wall).

Thank You. :)

# Answer
> 1 votes
As far as I know, the AI is actually misleading. The AI in Half-Life is very scripted, even though it doesn't appear to be so, which is why they can appear to exhibit intelligent behaviours.

---
Tags: algorithm, ai, path-finding, valve
---


# Question
Title: Should I give each character its own VBO or should I batch them into a single VBO?
I'm making a 3D first person game. Should I give each character its own VBO or should I batch all characters into a single VBO? What are the pros/cons?

# Answer
> 11 votes
This is really a choice between performance and flexibility, but I'll list my opinions about it.

**One single VBO**

The positive sides are:

* Just one draw call to draw your scene. This *increases* performance. Although your application may require multiple draw calls, you can still have a single VBO and let the count and offset decide your drawing.
* Not requiring state changes between your objects. This *increases* performance.

and the negative sides are:

* Hard to manage, although this depends on how you write your code, if it's properly designed etc.
* By saying *hard to manage* I mean stuff like update the VBO, set correct offset for every object etc.

**Individual VBO:s**

The positive sides are:

* Easy to implement.
* Easier to manage from the beginning.

and the negative sides are:

* Lots of state changes. This decreases performance.
* Lots of draw calls. It will decrease the performance.

**Summary**

I'd recommend you to profile your application; get your real bottleneck in data you can see. Premature optimization can be shown (in this case) as unnecessary. However, that being said, if you'd discover a real performance loss in your application, given the *individual VBO:s* scenario, you can start implementing a single VBO.

However, as long as it's not needed (the number of objects are low, not many state changes overall, etc) I'd recommend to go with individual VBO:s unless you see that's not gonna work.

**Edit**

I forgot to mention that it'd be alright with multiple draw calls. The most important thing in performance critical times is to keep the state changes at a minimum. You can simply set the number of indices to process and an offset for every draw call, and this is fine. But however, keep state changes as low as possible and make as few draw calls as possible, that's the big *hello* of this answer, or at least what I tried to say.

---
Tags: opengl, vbo
---


# Question
Title: What popular/famous games are written in C?
It is very similar to this question: https://gamedev.stackexchange.com/questions/3789/famous-games-written-in-java

Does anyone know of any popular or famous games only written in C?

# Answer
> 14 votes
Doom, Quake, pretty much all id games up until id Tech 4.

# Answer
> 8 votes
Cryptic Studios's games - City of Heroes / Villians, Star Trek Online, and Champions Online (and presumably Neverwinter Nights, but I can't vouch for that 100% since I don't work there anymore) - were written in C.

# Answer
> 1 votes
Lots of Jap/PS1/DC games. Also Soul Reaver 1, parts of Soul Reaver 2 and there was quite some plain C code in Tomb Raider: Legend.

---
Tags: c, game-industry
---


title: Container classes in tile-based games.

text:
# Question
Title: Container classes in tile-based games.
I've recently begun working on a tile-based tactical game, and I have questions regarding a couple of key moments.

Is it feasible to organize the tilemap as an array of containers, which can hold the game objects? What are the pros and cons of such an approach? Should I make a single container class for all the game objects, such as characters, walls, and terrain, or try to break it down to separate container types for every single game object class?

Any examples of a container capable of storing objects of several different classes will be greatly appreciated.

# Answer
> 13 votes
> Is it feasible to organize the tilemap as an array of containers, which can hold the game objects? What are the pros and cons of such an approach?

I would use `std::vector<Tile>` or similar. I don't see the need for an array of containers or for multidimensional containers (unless perhaps you have multiple independent layers of tiles). Even a simple plain array of `Tile` objects would work fine, if you must (although I find the use of vectors far more convenient. You can use a single-dimensional container as a 2D one just fine, you simply make it contain `width * height` items and to access the tile at `(x,y)` use indexing math like `container[x + (y * width)]`. Generally one will encapsulate this indexing math behind a tilemap class or some other kind of abstraction.

The reason for preferring a single-dimensional vector is that a multi-dimensional vector gives you no tangible, significant benefit over a single-dimensional one, but a single-dimensional vector provides the additional benefit of keeping the elements all contiguous in memory, resulting in better locality of reference and cache coherency. A vector-of-vectors-style multi-dimensional array does not have this property, nor does the sane form of a dynamically-allocated multi-dimensional plain array (although one with compile-time bounds will, but that is of limited utility in this scenario when you'll presumably want to read your data from a file eventually).

Of course you could achieve that coherency via pooling allocators as well.

> Should I make a single container class for all the game objects, such as characters, walls, and terrain, or try to break it down to separate container types for every single game object class?

If every object in your game can be treated exactly the same, then it may be more efficient to create a common base interface for them, and manage them all as a big list of that base interface. As the complexity of your game objects grows, this may be less true and it may be more beneficial to split them out into different lists based on type or other criteria.

As a rule of thumb, if you keep objects that will be processed similarly with each other organizationally, you'll be able to process them more efficiently. "Processing" here includes not just what they do when they `Update()` every frame, but also how long they exist in the game world, what their lifetime management policy is, whether or not they must be processed in a certain order, et cetera. Keeping them together may also improve locality of reference and allow you to spread processing out onto multiple threads, which can be a big win for performance.

> Any examples of a container capable of storing objects of several different classes will be greatly appreciated.

Almost any container can; it matters more what you store rather than what you store it in. If you take advantage of polymorphism, you can implement a base class or interface

```
struct Base{
  virtual void DoThings() = 0;
};

```

which everything to be stored together inherits from

```
struct ChildA : Base {
  void DoThings() { /* ... */ }
};

struct ChildB : Base {
  void DoThings() { /* ... */ }
};

```

you can create a `std::vector<Base*>` (as just one example) and store pointers to `ChildA` and `ChildB` in that vector and treat them uniformly by way of their common interface.

You should also consider that its generally good practice to divorce your rendering and game logic code. The effect of storing different classifications of game object in different ways should have no impact on the organization of your rendering queue; you'd still want that to operate on (essentially) a single list of its own type of object (for example, sprites in a 2D game). The most straightforward way to achieve this is to store a pointer or reference to the renderable component (sprite, or some higher level construct if needed) inside the game logic components.

# Answer
> 2 votes
For your tilemap, I'd recommend either using a C-style multidimensional array wrapped in your own class, or using a multidimensional `std::vector` for the same purpose. You can then read in this at run-time from your map file (how you do this will depend on how you design your map file).

With regards to storing the entities in a game, it's really up to you, I'd suggest a container (probably a linked list is best in this case because you don't really want a contiguous memory block, and also you will no doubt regularly be adding and removing entities etc. so the amortized constant time may be of some advantage here, or perhaps `std::deque`, or even std::map depending on how you want to implement it) to store a pointer to each of your entities (which should derive from some base class, probably `CBaseEntity` or something like that, again depending on how you choose to structure it. Have a base entity to derive from will also help you in terms of your rendering pipeline as well, as you can call some derived `Render()` function for each entity in the container.

The reason I would use one container rather than several is that it minimizes the number of loops needed in your rendering pipeline. It allows you to perform global entity operations, and if you use an std::map, or std::multimap (or their unordered counterparts) you can still make sure you only choose the entities you are interested in for entity specific proceedures. Moreover, it minimizes overhead (not that is much of an issue with only say, 20 types of entity, but if you move into several hundred types of entity (which could be quite easy depending on how in-depth your game becomes then you could give yourself quite a bit of overhead).

An example of a game engine which keeps all of it's entities in a single container would be the Source engine (used by half-life, half-life 2 etc.)

Hope this helps! :)

---
Tags: c++, architecture, tiles
---


# Question
Title: Optimizing a mesh for voxel cube landscapes
Playing around with creating minecraftish/lego world landscapes in Unity 3D (procedurally generated voxel landscapes with cubes), I'm finding that the meshes created for these landscapes take up a LOT of memory. The mesh currently only consists of vertices for visible sides of a cube. Memory usage for a complex terrain may take 6 or 7 hundred megs.

These meshes could be optimized, but I'm struggling to find a decent algorithm to do this.

The algorithm has to take into account that you don't want to "merge" blocks that are of different terrain types. I guess a really simple start might be to just process all blocks along one axis, and do extra sweeps for the other two axis.

I need to keep the mesh shape, that is no merging of vertices to the point that empty or solid space is changed. The reason is, there may be creatures/etc that still need to navigate around the mesh. So I can't just create a really low detail, distorted mesh.

Any thoughts/suggestions/tips on this?

# Answer
My question is:

Why would you need the mesh itself to do creature movement?

Can't you do the pathing calculation on a 3d matrix of id's?

I think Minecraft uses a 3d matrix with 4 bits pr block. It also only simulates creatures a certain radius around the player.

You could store your chunks in a oc-tree structure, where each chunk is compressed.

If you keep the compressed data in RAM you can decompress the data quite quickly when needed.
> 5 votes

# Answer
How about using an octree to store the terrain?

E.g. air = no node, all other terrain types would have a node with the terrain type.

When inserting/removing nodes, you could check if all eight children of each node on the modified tree path have the same terain type and merge them if needed. That way, big blocks of the same material would only take up one node.
> 1 votes

# Answer
Are you only creating the cubes for parts of the geometry the player can see? That would be my first step. Depending on the size of your terrain you don't have to have the entirety of the world loaded/drawing/visible/whatever.
> 0 votes

---
Tags: 3d-meshes, optimization, voxels
---


# Question
Title: How can I keep a GUI on-screen without moving/resizing it according to camera motion?
I'm trying to make a GUI library with SFML, and everything's done except for one problem: making the interface stay still even when the camera moves or zooms in and out.

This would be easy to fix if zooming wasn't possible, but zooming out means having to scale the contents of the interface up so it doesn't shrink, which causes it's text/images to become blurry.

Does anyone have a way to get around this issue (preferably only using SFML as I don't want to make my library OpenGL-dependent)?

# Answer
After you've rendered the world, reset the camera position to something more useful for UIs. Then render the UI. Next frame, put it back to the world position before rendering the world. And so forth.

By "camera position" I really mean "transformation matrix". Nobody says all rendering has to go through the world transformation.
> 13 votes

# Answer
In SFML terms, you should be changing the active sf::View on your RenderTarget between rendering the world and the GUI. Your world `View` should be whatever is most convenient for your world rendering and centered on your player position; your UI `View` should be pixels or some standard resolution, rooted at the origin.
> 7 votes

---
Tags: c++, gui, sfml
---


# Question
Title: Examples of interesting implementations of character stats?
I've got this BBG going ( http://ninjawars.net ), and the character stats currently are simplistic. I'm looking to add a few stats to the current 1/2 (strength and maximum hitpoints, essentially). I've come up with: (strength (unchanged), speed, stamina, and some others that are somewhat interesting wildcard stats). However, I'm not satisfied with how boring the effects of some of these stats are, because they're very linear. Better stat, better effects of the stat, but the stats don't interact with each-other, there's no Rock-Paper-Scissors interaction, having more is always better all the time.

So what I'd really like is to see examples of interesting character stats or effects of stats?

Examples that I can think of off hand:

Call of Cthulu's Insanity stat (things get really weird/chaotic if you start losing sanity)

White Wolf stats, to a certain extent (the stats themselves have some basic effects, and all skills effectiveness base themselves off of stats as well)

What are some other ways people have used stats to check out?

# Answer
> 5 votes
I don't think it's relevant to what you're doing, but the most interesting way I have seen so far is in Amnesia: The Dark Descent (by the makers of Penumbra).

The basic principle of the game is that the character does not have any memory of what is going on, and you are alone in a castle that is alive - that is, something is chasing you, but you don't know what. You have to try to escape, whilst avoiding the monsters that will chase you around and stopping yourself literally going insane.

You cannot actually fight - one of the reasons its so scary (meeting a monster is certain death) - so there's less attributes, but you have 2: **Health** and **Sanity**. Instead of having '100/100 health', you simply get a description - 'A few minor cuts and bruises' or 'Struggling to walk'. And then low sanity made the screen go all weird.

I much preferred this over the standard 'you have 15/200 health left'.

An idea I was planning on using for my RPG:

Instead of a 'hit points', 'constitution', or 'strength' stat, you instead have 'upper body muscle' or 'arm dexterity'. It's very much a BODY PART + STAT system, but it makes more logical sense. I mean, if you worked out at a gym in a game running, then you would have much stronger legs, but having your hit points going up would be very generic - *I have strong legs, so therefore getting hit in the chest doesn't do as much damage.* In the same kind of way, a high strength would usually equate to a direct damage bonus. With a sledgehammer, this makes sense, but there's only a certain amount of power you can apply to a katana, say.

EDIT: I have remembered another stat system I was very fond of: **Fallout 3.**

It had your usual 'base stats' - strength, endurance, luck, perception, agility, intelligence etc. Then there were a number - I think about 23 - other stats. These stats actually defined your character more. For example, a high strength meant you could carry more equipment, but not necessarily meant you could do lots of damage with a baseball bat. In the same way having a high energy weapons meant you could do a lot of damage with a laser rifle, but wouldn't necessarily mean you were very agile.

Then each of the base skills had a trickledown of a few points to other skills - every point in strength gave about 1.5 points to melee weapons, for example. This made me as a player consider my stat choices much more than 'durrr shove it all in \< weapon I'm using \>'.

# Answer
> 6 votes
The way Shadowrun's core stats shook out, if you think about them abstractly, was interesting to me:

```
               Offense      Defense      Speed
Physical       Strength     Body         Quickness
Mental         Charisma     Willpower    Intelligence

```

If you have underlying abstract roles defined for your stats like that, the ways they wind up used come very naturally.

The main thing I don't like about that stat layout is that "perception" winds up being the same thing as "intelligence", which frankly lacks verisimilitude in a big, bad way.

# Answer
> 3 votes
So you're speaking about some Rock-Paper-Scissor interaction? The simplest and wide-spread way to do this, would be by using *character types* instead of character stats for this behaviour. I.e. every character has to be either "Rock", "Paper" or "Scissor" and depending on which types are fighting you can multiply your stats with a certain factor.

I.e.

```
if(opponents(rock, scissor))
rocks_strength = rocks_strength * 1.5;
if(opponents(paper, scissor))
scissors_strength = scissors_strength * 1.5;
...

```

and so on. That's how I would go in your case. You can also add more complexity if your boost different stats for different types and/or add additional clauses (i.e. the stone gets doubled stamina if his opponent is a scissor with a higher strength)... There are *really* a lot of possibilities...

# Answer
> 3 votes
"Design Patterns of Successful Role-Playing Games" is a free (by-nc-sa) ebook dedicated to using the concept of patterns in the design of roleplaying games.

It is available through http://legendaryquest.netfirms.com/ (last item under 'downloads', or here: the pdf).

This tome of information is quite a tough read, but great for easing the design of roleplaying game systems and finding a common base in communication about them.

The book introduces a diagram language for modelling conflicts/tests in rpg systems visually and contains a bunch of sample diagrams of existing (pen and paper) rpg systems.

# Answer
> 2 votes
one possible solution would be to have some *basic* stats and some *derived* stats. For example you got strength (S) constitution (C) and mass (M). Hit point could come from C+M, while speed would come from S-M (mass could add to your basic hit point, but you're slower). if you got a derived stat (or bonus/malus) for falling, it could come from agility and mass, and so on.

regards
Guillaume

# Answer
> 1 votes
While Constantin's solution for player classes is valid, another possibility is to force the player to create his own class similar to what is done in Demon's Souls.

For those not familiar, with each level the player can add 1 point to any stat (speed, magic, strength, vitality, stamina, etc.). Now while this can lead to stats being linear and not giving an RPS type mechanic (a fully upgraded character will have access to all stats), you can limit the player's ability to do this by making the level scaling incredibly high at later levels or just limit them to a certain level so that all stats cannot be 99. In either case, you end up with players forced to lean toward speed, power, vitality, etc. types of builds which will create an RPS mechanic.

---
Tags: character
---


# Question
Title: How to do gradient transitions using slimdx?
I am making an image slide show using slimdx and c#. Till now I have done transitions using the matrix transformation but now I am trying to make transitions using some gray scale background image. Can any body please give me an idea how can i perform that or can post some code to give me an idea.

# Answer
If we first consider the simple case of having two images that as a whole fades from one image in a seamless fashion into the other image, this would be cheapest to express as drawing a quad with a pixel shader.

This shader would have a float shader parameter you set from your code in the range of \[0,1\]. You can then bind and sample your two textures and lerp between them based on this constant factor.

A value of 0.0 would represent 100% of the first image, a value of 1.0 would be 100% of the second image, 0.25 would be a quarter of the first and three quarters of the second, and so on.

You can then use additional textures to alter the value of this interpolation parameter, like:

* you could a grayscale texture which could act as an offset to this parameter,
* you could use the parameter to index inside a 3D texture or a texture array which would represent your wipe,
* you could use the parameter to translate the texture coordinates used to sample a gradient texture, so that the static gradient band appears to move across your image.
* you could do something entirely else - with programmable shaders your imagination is the only limit (barring shader complexity limits from the shader model, of course).
> 0 votes

# Answer
Looking at the SlimDx documentation, I think more information could be useful like what classes you are using to diplay your images?

Generally for a fade-in/out transition you can use a quad with a texture or just a plain color, and using the 'tint' Color, you can make the quad more or less transparent.

If you are familiar with shaders, you can make a shader take multiple Textures and a float as input, and you can then easily calculate the needed mix.
> 1 votes

---
Tags: c#, directx, slimdx
---