# Question
Title: Actor and Sprite, who should own these properties?
I'm writing sort of a 2D game engine for making the process of creating games easier. It has two classes, Actor and Sprite. Actor is used for interactive elements (the player, enemies, bullets, a menu, an invisible instance that controls score, etc) and Sprite is used for animated (or not) images with transparency (or not).

The actor may have an assigned sprite that represents it on the screen, which may change during the game. E.g. in a top-down action game you may have an actor with a sprite of a little guy that changes when attacking, walking, and facing different directions, etc.

Currently the actor has `x` and `y` properties (its coordinates in the screen), while the sprite has an `index` property (the number of the frame currently being shown by the sprite).
Since the sprite doesn't know which actor it belongs to (or if it belongs to an actor at all), the actor must pass its `x` and `y` coordinates when drawing the sprite.
Also, since a actors may reset its sprite each frame (and usually do), the sprite's `index` property must be passed from the old to the new sprite like so (pseudocode):

```
function change_sprite(new_sprite)
    old_index = my.sprite.index
    my.sprite = new_sprite()
    my.sprite.index = old_index % my.sprite.frames
end

```

I always thought this was kind of cumbersome, but it never was a big problem.

Now I decided to add support for more properties. Namely a property to draw the sprite rotated, a property to draw it flipped, it a property draw it stretched, etc. These should probably belong to the sprite and not the actor, but if they do, the actor would have to pass them from the old to the new sprite each time it changes... On the other hand, if they belonged to the actor, the actor would have to pass each property to the sprite when drawing it (since the sprite doesn't know which actor it belongs to, and it shouldn't, since sprites aren't just meant to be used by actors, really). Another option I thought of would be having an extra class that owns all these properties (plus `index`, `x` and `y`) and links an actor with a sprite, but that doesn't come without drawbacks.

So, what should I do with all these properties?

# Answer
> 1 votes
A common way to deal with the problem you're describing is to do this:

```
class Transform
{
   public int x;
   public int y;
   public float rotation;
}
class Actor
{
   public Sprite s;
   public Transform t;
}
class Sprite
{
   public Transform t;
}

```

Now your data is encapsulated in one class ref'd by both Actor and Sprite. As for that separation, yes I think that's a good idea as the actor is essentially game logic, and the sprite is a view -- they are in this sense completely decoupled for cleaner code.

So you can take that as a more general, "yes" to your final suggestion. Push things out into intermediary classes where appropriate.

# Answer
> 2 votes
Each object should own its own properties. If other objects need to know those properties, let them query for them.

Your sprites probably don't have an intrinsic position, and they don't know how to get a position to be rendered because they may have to get that information from more than just Actors. So, you need a class that mediates between them. You might have an ActorView that holds a reference to the Actor and contains an instance of Sprite. When the Actor moves, ActorView is notified, and knows where to draw the sprite. The ActorView could also hold the current frame of animation, etc.

# Answer
> 1 votes
Classes and objects are just bundled functionality, nothing more. And that way you should work with them.
Ideally you should build your classes around composition. The more advanced object should consist out of multiple smaller objects, and do all the communication needed between the smaller objects. The smaller objects should do nothing on their own and should know nothing about their parent. They just should do what is wanted from them.
In the case of this question that would look like this:

```
class Actor
{
  Sprite sprite;
  int x, y;
  float rotation;
  [...]
  void draw()
  {
    sprite.draw(x, y, rotation);
  };
  void update(dTime)
  {
    sprite.advanceAnimation(dTime);
    [...]
  };
  [...]
}

```

# Answer
> 0 votes
Whenever you encounter a situation like this, there are a couple of questions you can ask yourself to determine the what the best structure is going forward:

* Is one class a more complex version of the other class?
* Should one class know about the other?
* What overall purpose is the class supposed to serve?
* Is one class a utility to be used by more complex class?

If you answer yes to the first question, then inheritance is what you're looking for. For example, a regular sprite, or a sprite that supports multitexturing. In the case you're describing, the answer is probably no, an `Actor` is not a more complex `Sprite`. I think you are right that the `Sprite` class should not know about the `Actor` class, because, tying into the fourth question, the `Sprite` class is really a rendering utility for the `Actor` class; the Actor class relies on the `Sprite` class to draw itself on screen.

So, the `Actor` class should contain an instance of the `Sprite` class, in the same way that a `GameObject` in a 3D engine would have a `Model` to represent itself in the world.

To get to the specifics of your question, it seems like the root of your problem is your concern in how much maintenance the `Actor` class is going to have to handle for its `Sprite`. You mentioned that the `Sprite` instance often changes every frame, and the `Actor` would have to be responsible for updating it (I'm guessing this is for 2D animation?). I think this is where your structure goes wrong. What I would suggest is to create an `AnimatedSprite` class, which is responsible for the update of it's current on-screen sprite, and would store the 'index' of its animation. It's API could include functions such as `animate`, `stop`, etc; everything you might want an animated sprite to do. For position, your `Sprite` class' draw-call should take in the position where it is to be drawn.

What's most important is that a whole class instance inside of your `Actor` class should not have to be reconstructed every frame. If that becomes necessary, you should probably look for areas of improvement in your architecture.

---
Tags: sprites, gameobject, oop
---


title: Best approach to 2D racing game AI?

text:
# Question
Title: Best approach to 2D racing game AI?
I have no experience in AI **at all**, but I would like to know how I could do this?
Even if the AI just followed a path how could I do this?

# Answer
My first thought naive approach would be to create a list of points corresponding to the coordinates of the track curves (probably more points would be needed to prevent the AI keep going against walls after an unplanned collision with another car). When the AI car is close enough to the next point, you would put it (the point) in the end of the list. All the AI car would need to do is to always go in a straight line in the direction of the next point in the list.
> 2 votes

# Answer
Yes, make a type of path that the car follows. First, you need to make the car just drive. (Make the car drive forward forever). Create a rectangle at each turn on the track then make if statements for when the AI car intersects them. When the AI intersects them(the rectangles) make it rotate according to where it needs to turn.
> 0 votes

---
Tags: 2d, ai, racing
---


# Question
Title: Z Order in 2D with orthographic projection and texture atlas
I am working with a 2D game in OpenGL ES and have a question about z-order together with a texture atlas.

I am using an orthographic projection because I want pixel-perfect rendering of 2D sprites, however from what I can determine the draw order is really the only thing that will determine which textures (sprites) appear above or below their neighbors.

That is, the "z-index" is a function of the order in which the textures are drawn as opposed to the z coordinate on the vertex array being drawn.

So.. I have a texture atlas to save binding multiple textures for each draw call but this immediately creates a problem if there is more than one atlas in play. If I need to draw textures from more than one atlas (typically the case if I have too many sprites to fit in a single atlas of a reasonable size), then I can't maintain a "draw order" across atlases unless I want to bind/unbind the atlas textures more than once.. which kinda defeats the purpose.

Does anyone have any clues as to what the best approach is here? Currently I'm running under an assumption that I will have to declare different fixed "depths" (e.g foreground, background etc) in my 2D scene and assume that the z-order for sprites at a given depth is the same. Then I can have as many atlases as I need at each depth and simply draw the depths in order (along with their associated atlases)

I'd love to hear what other people are doing.

# Answer
> 3 votes
Detailed illustration:

```
 0   0.25      1
 +----+--------+  0  <-- this is your sprite sheet
 | A  | B      |
 |    +--------+  0.5
 |    | C      |
 +----+--------+  1.0

```

Let's assume that you have a sprite sheet with defined order of sprites C,B,A

The following methods allow you to draw the sprites in any order using z-buffer.

* instead of defining in the sprite sheet only 2 coordinates per vertex (u & v), add a third attribute 's' for depth to each texture coordinate:
+ A = \[0,0, .6\], \[0.25, 0, .6\], \[0,1, .6\], \[0.25, 1, .6\];
    + B = \[0.25, 0, .5\], \[1.0, 0, .5\], \[0.25, 0.5, .5\], \[1.0, 0.25, .5\]
    + At vertex shader you can copy the last value from the vertex attribute (the constant .5 or .6) to the z-component of gl\_Position. Then the rendering pipeline will perform depth test for each quad / triangle to be drawn and always draw B on top of A.

Alternative: Add the 'depth' to u-coordinate.

* A = \[5.0, 0\], \[5.25, 0\], \[5.0, 1.0\], \[5.25, 1.0\]
* set texture wrapping so, that u-coordinate *wraps*
* then 5.0 will be handled as 0.0
* set v-coordinate handling mode to *clamp*
* Then 1.0 and 1.1 and 5.0 will be treated as 1.0
* again in vertex shader copy the *integer* part of u-coordinate to z-value (and multiply e.g. by 0.01 because |z|\>1 will be clipped off...

The other alternatives in the first draft assumed possibility to access texture data in vertex shader. This may be prevented in some or most environments, so we can skip that...)

* Option 3: Add the depth to vertex data

Do you need more than 1 sprite sheet? You can access 6 sheets with a cube map:

```
       +-----+
       |     |
       |     |
 +-----+-----+-----+-----+
 |     |     |     |     |
 |     |     |     |     |
 +-----+-----+-----+-----+
       |     |
       |     |
       +-----+

```

A cube has 6 faces and CUBE\_MAP texture combines 6 individual sheets in a single texture. The texture coordinates are 3D and the face is selected by the dominant coordinate: if |x| \> |y| && |x| \> |z| then either 'left' or 'right' face is used. if |y| is the dominant coordinate, then top or bottom sheet is selected.

---
Tags: textures, opengl-es
---


title: Data for bingo tickets

text:
# Question
Title: Data for bingo tickets
Is there a data source for 90 and 75 ball bingo tickets? rather than coding to generate the tickets myself just trying to find a source to save me the time.

Many thanks

# Answer
Googling for "90 ball bingo ticket generator" gives plenty of relevant hits.

I don't think there are any "official" bingo tickets out there though, but writing a generator is probably rather trivial..

The most obvious thing would be to make completely random cards, which, due to the way bingo works, would work just fine. With a bit more effort it would be possible to generate a set of cards that make sure that for a given number of players, each number appears the same number of times - to avoid the awkward situation where everybody in the hall shouts 'bingo' at the same time..
> 1 votes

---
Tags: data
---


# Question
Title: How to access variables of uninitialized class?
So I've gone with a somewhat singleton approach to my game class:

```
#include "myGame.h"

int main () {
    myGame game;
    return game.Execute();
}

```

But now I need to define a class that accesses variables in the instance of myGame.

```
class MotionState {
    public:
    virtual void setWorldTransform (...) {
        VariableFromMyGameClass++;            //<-- !?
        ...}
};

```

I'm trying to integrate this class into my project from an example that just uses globals. How can I access variables of myGame class in the definition of new classes? Should I give up on my singleton approach?

# Answer
If you want to continue using the singleton approach, you could benefit from a proper implementation of the singleton design pattern in C++.

Essentially, you define your class as follows:

```
class myGame {
private:
    static myGame* _instance;
    // Other private members.

public:
    static myGame* Instance();
    // Other public members.
};

```

And then the `Instance` function looks like this:

```
myGame* myGame::Instance() {
    if (!_instance)
        _instance = new myGame();

    return _instance;
}

```

This way, you can call `myGame::Instance()` to get your singleton class, and invoke whatever modifier or function you need, from anywhere in your code.

You might also be interested in: https://stackoverflow.com/questions/1008019/c-singleton-design-pattern
> 6 votes

# Answer
My thoughts-

A singleton implementation is a great way to just have one instance. But if your interested, another way, which I use ALL the time is a completely static class. By declaring all your functions and variables in your "MyGame" class as static you can just use the '::' operator (ex: MyGame::VariableFromMyGameClass++;) Also, as an added benefit, you can force no object creation of the class by declaring the default constructor 'private'.

Just thought I'd contribute :)

-MasterBaldwin
> 2 votes

---
Tags: c++
---


title: Making a game engine or using Unity3D?

text:
# Question
Title: Making a game engine or using Unity3D?
I was wondering, which one would benefit me the most? I have as much time as I need to make a game engine and rapid development does not appeal to me. Unity3D is easy, but how much will mastering Unity3D gain to my knowledge of game development, compared to making a game engine?

# Answer
> 7 votes
Your question let assume that you want to gain knowledge in game development. As I understand it, you want to make games but don't really know what is the best for you.

Long story short: **don't ever believe that you have "enough time" to make a game engine**. This is a hard work. A very hard work. Depending of your type of game you have to master several specifics fields of knowledge.

If you want to learn how to make games Unity is a great tool for that. Thanks to it you will learn concepts very specific to video game development without having the pain to build your own tools, render engine, physics engine...

If you have "enough time" (which I'm not sure) to make your own engine, you surely have enough time to look at UnityEngine in order to make an opinion and see if it can be useful for you.

# Answer
> 0 votes
Never make a game engine :)

Maybe after your 5th game you can start thinking about creating tools which can help you.

---
Tags: unity, c++
---


title: What makes puzzle games addictive?

text:
# Question
Title: What makes puzzle games addictive?
I'm currently developing a puzzle game for Android that is sort of along the lines of Alchemy.

I was wondering what makes games like Alchemy or Bejeweled so addicting? How do I keep players interested in the game to want to play it over and over? Is it the scores? Level advancement? The challenges? What should I be doing to try and keep a player engaged with a puzzle game since they are often quite repetitive?

# Answer
A puzzle game like Bejeweled or Tetris has randomly generated "levels", usually with a slow progression in difficulty. That alone can make a game interesting. Trying to get as far as possible, getting a "lucky streak" or scoring the most points.

One thing that's really important is that the gameplay feels right. Controls should be simple and intuitive, graphics and sound should support and enrich the gameplay. Clearing a level or scoring multiple points with one move should look and sound great, so that the player gets some sort of audiovisual reward.

It's a bit different with puzzle games that have pre-defined levels like physics-puzzles or games like "Slice it" or "Trainyard". The main goal there is to *beat the game*, eg. complete all levels. Additional replay-value can be added by adding better scores for fast or "flawless" solving of the puzzle.

Another important factor is progression. Either by trying to beat your own scores or scores from other players in a leaderboard. Once you mastered a game and you have the feeling that you can't get better, you'll most likely also lose interest in it.

The most addictive puzzle-game I've played recently is probably Puzzle Quest. It combines a Bejeweled-type of game with a fantasy story and RPG elements. Not only the puzzle-solving is addictive, you also want to progress in the story and "level-up" your character... addictiveness overload ;)
> 10 votes

# Answer
From a game developers point of view, I would say the most important thing in creating an addictive and fun game is to prototype early! And iterate your ideas, tweaking gameplay in the beginning stages of development, not the end. That way, if you find that the game is not fun and addictive, then you could chuck it away, and not worry too much about wasted resource.

Also user testing and hallway testing is important. Usually the developer is "too close" to the game to make good game-play decisions.
> 4 votes

# Answer
A huge deciding factor for me in whether a game is addictive or not, is how long it makes you wait at critical points, such as when a game is over, how long does it take and how many clicks does it take to get you to the starting point of a new game?

Too many screens and too many delays at this point make it so that players just couldn't be bothered playing another round.
> 4 votes

# Answer
Steve Yegge (everybody's hero) talks about collecting guns in borderlands, and the token economy. Collecting stuff seems to be a big thing. Also, flOw teaches us that gradual ramping up of difficulty is important.

Although (as Krom points out), these are not particular to puzzle games. The game flOw's base thesis I've not read, but the idea's are embodied by the concept of Flow in Psychology, gradual skill and difficulty ramping up to maintain interest by the player. Although Steve talks about collecting guns, it is the collection of "stuff" and it's rarity that may keep people coming back. Steve also talks about the splitting of leader boards. The more metrics we have to measure ourselves against, the more effort we may make to meet those metrics, or to go crazy in one. combinations of a certain colour or shape? Recent success 10000000 on iPhone has has a shitty match three game but has a meta game on top of it, adding a story.

None of these things have any impact on the base mechanic of Alchemy, but without some constant shift of difficulty or peripheral activity, the mechanic will be learnt, understood, mastered, and left behind.

Krom, is that better?
> 0 votes

---
Tags: game-design, puzzle
---


title: Online Android Game Server

text:
# Question
Title: Online Android Game Server
How to create a game server for Online Android Game? I was thinking to create a Multiplayer Scrabble Game in an Android composed of two to four players.. thanks for the replies. it can help to my thesis. thanks.

# Answer
> 1 votes
You've got a couple of options:

* Webservices-\> Rest services (for non realtime games like scrabble and keeping highscores etc)
* Tcp Sockets (for reatime games)

Both can be programmed in languages like C# and java, webservices also in php

---
Tags: android
---


title: Will setInterval give me Delay?

text:
# Question
Title: Will setInterval give me Delay?
I am setting up a JavaScript Server for my Game.

Am I understanding this correctly:

If I use setInterval to call a function every second, and takes 2 seconds to process. Then I am going to "stack up" requests indefinetly the Client will become more and more out of sync?

If I use setTimeout, and specify 1 second. Then the function will run (again, lets say 2 seconds) and then start the timeout. And not stack up requests.

*Edit: I am doing Pathfinding and sending it to the Client. Thank you for all the help people. I think using the Callback is the best option for this.*

# Answer
What you are trying to do sounds like a typical case for callback functions instead of SetTimeout/Interval. Especially with network communication (Longpolling, etc.) SetInterval is a bad choice.

Instead of using `setTimeout` or `setInterval` in most cases it's more appropriate to make use of javascripts asynchronical nature and use callbacks.

This means that you hand over a function that is executed as soon as the first function has finished.

Here is a brief explanation on how to use callbacks. Or you can read several question about that topic on Stackoveflow (e.g. here).
> 4 votes

# Answer
When using `setInterval`, you have as much time as you've specified for the interval parameter, to do the work. It's not a "blocking" wait, the timer runs in parallel with your code. So just set it to something safe, like 2 or 3 seconds. That's your period in which you can get things done. This is how all JS games work. You should be able to test this easily in the browser, just set up a small program that adds a million numbers in place of your 2-second task, have it run every `n` seconds, and see how that affects `setInterval`'s firing. **EDIT** I think what you'll find (if you write a very simple test) is that if you have something that is blocking for 2 seconds, but your interval is set to 1 second, then yes, as soon as your first function call completes it's going to jump straight into the second one (because it will have already backed up), but the timer will fall further and further behind. In any real time application, you *have to* be able to guarantee that work is going to be completed within some maximum time period. This is *not an option*. For more information, read up on Gaffer's Fix Your Timestep which discusses issues of timing in detail.

*It shouldn't be taking you that long to process anything in a game* (client or server). If it is, then your code is either highly inefficient or it needs to be broken up into individual "tasks" with higher granularity, which can then be fed into the function. That way, you'd have no problems with `setInterval`. Just a thought.

**Just to add...** It seems to me that if you tell us what you are trying to achieve, we can help you find the best solution. Right now, I'm feeling that what you're attempting is missing the mark.
> 2 votes

---
Tags: javascript
---


title: Voice artist for a game for kids

text:
# Question
Title: Voice artist for a game for kids
We're making a game for kids which should include about 50 spoken phrases. I'm asking for help in finding the right voice artist / studio for this. I've tried searching the web but couldn't find anything that would make me sure that it would work for us or games in general. So I'm looking for references from those of you who had a successful collaboration with artists or studios. Any help would be appreciated.

# Answer
> 2 votes
It's just an idea. I haven't tested it. But isn't it possible to simply record it and edit the record using some filters/effects to make it sound like you want? Tools like Audacity or GarageBand might be a point to start.

I think that the main trick is to have a soft low voice, so try to pull down the pitch of the recording with one of those tools. And when recording, try to speak slowly.

As I already said, that is what I should give a try. Not sure if the results will be good. Good luck!

---
Tags: sound, assets, voice
---


# Question
Title: Is ActionScript 3 used by Serious Indie Developers?
This question is for dedicated independent game developers:

My dream is to be a game developer. I am a senior in high school who has taken Computer Science for all four years. I have used Java the whole time, but last year I started using PHP and ActionScript 3 (with Flixel). I also used Game Maker for a brief period. I apologize for this, I wanted to get that out of the way and clarify the fact that I have experience of some kind with game development.

I am stuck at the moment because I don't quite know what language to use to develop games at a professional level. I am seriously interested in becoming a dedicated game developer, but this issue is really bothering me. I would like to know what the best option would be for my case, based on your experiences. Any advice is appreciated.

Things to consider:

* I am only interested in making 2D games (I am not worried about 3D support)
* It would be ideal to use something that can be ported to multiple platforms (so as not to run into this problem later)
* I can't seem to figure out what the industry likes to use

So far, this is what I have:

* I can't decide if it would be wise to stick with ActionScript 3, or move to C++
* I know Flash would be for browser games, but what if I want to make a downloadable game, like Plants Vs. Zombies or Super Crate Box? Would Flash be a smart choice for standalone games, or did they use something else?

Thank you for reading this, as I would like to stop worrying about this and make some games! Also, I hope this wasn't all over the place :)

tl;dr Should I move ahead with AS3 or use something else i.e. C++

# Answer
Flash is dying. Whatever some Flashers may tell you, HTML5 is slowly taking its place. Slowly, because HTML5 still isn't really production ready in many senses, for full-fledged and straightforward game dev. You can see solid stats for the shift over the last year if you look (for example) at those jobseeking sites that record these things, Flash demand is falling fast. And that does include games. The main reason? Mobile compatibility. There is the possibility of using Mobile AIR apps to continue developing in AS3, but the shift to HTML5, Unity or native apps seems stronger at the moment. Flash's semi-retirement has contributed to lack of visibility for Mobile AIR.

But, for now, at least on the desktop, Flash still provides a solid, fast, even GPU-accelerated (as of FP11) platform for game building, and for rapid prototyping of ideas for larger games -- say those that will later be built from the ground up in C++. The best part is it's old hat, you can easily use vector or raster graphics, if using Flash IDE you can code and draw in it... etc. All these things make development vastly more rapid than HTML5 (for instance).

More important is not to tie yourself too closely to one language, TBH. There are some benefits to being a specialist, but I think it's better to score 9/10 on 5-6 languages than 10/10 on 2. In many ways, that makes you a better programmer, because you become more focused on assembling patterns than on assembling syntax. In other words, it abstracts your understanding, which is always good.

As for what else you might choose? That's going to depend on your research and specific needs (eg. raw speed, web deployment, GPU capabilities, mobile support etc. etc.).
> 8 votes

# Answer
Flash (as3) is ideal for web games though there are flash players which allow them to be bundled into a native application. In this way, you'll mess up with using different players for different platforms, which may not be guarenteed to run consistent on every platform.

My opinion is to use a cross-platform game library with C++ though I'll stick with java. It's your personal preference over which method to use.
> 2 votes

# Answer
I'd recommend you check out Haxe. It's a language very similar to AS3 but with major improvements, so you'll be on familiar grounds. The main thing about Haxe is that it compiles to many different platforms and source targets, some of which are:

* cpp for windows, linux and even iOS and Android (and others)
* neko
* javascript
* flash
* a few more which aren't as useful for games

Haxe has a library very similar (if not identical) to the flash API, called NME, which works on all of these platforms. There are also flashpunk and flixel ports and they are very up to date with their as3 counterparts.

I've been using it for the past few months and I like it, though it has some non-serious quirks. The documentation is mostly good and the community is awesome and helpful.
> 2 votes

# Answer
You will have to learn multiple languages, so don't worry about this. Indies often code something in Flash first, then rewrite it in Unity/C# or ObjectiveC or Java or even C++ if they want to deploy to different platforms. Learning new programming languages is relatively easy when they're as similar as the above ones. The hard part is understanding the concepts and being able to make a good game with one.

So while you're still learning, just make the games. When a game is good enough to sell, then you can start thinking about what sort of platforms you want to be on, which starts to dictate the languages you can use.
> 2 votes

---
Tags: c++, actionscript-3
---


# Question
Title: How to alter image pixels of a wild life bird?
Hello so I was hoping someone knew how to move or change color and position actual image pixels and could explain and show the code to do so.

I know how to write pixels on a surface or screen-surface

```
usigned int *ptr = static_cast <unsigned int *> (screen-pixels);

int offset = y * (screen->pitch / sizeof(unsigned int));

ptr[offset + x] = color;

```

But I don't know how to alter or manipulate a image pixel of a png image my thoughts on this was

How do I get the values and locations of pixels and what do I have to write to make it happen?

Then how do I actually change the values or locations of those gotten pixels and how do I make that happen?

any ideas tip suggestions are also welcome!

```
  int main(int argc , char *argv[])
    {

        SDL_Surface *Screen = SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);

        SDL_Surface *Image;

        Image = IMG_Load("image.png");

        bool done = false;

        SDL_Event event;

        while(!done)
        {

            SDL_FillRect(Screen,NULL,(0,0,0));

            SDL_BlitSurface(Image,NULL,Screen,NULL);

                while(SDL_PollEvent(&event))
                {

                    switch(event.type)
                    {

                            case SDL_QUIT:
                            return 0;
                            break;

                    }

                }

                SDL_Flip(Screen);

        }

    return 0;

}

```

# Answer
> 3 votes
I will assume you are reading a 32 bit RGBA surface, which means each pixel will have 8 bit for Red, 8 bit for Green, 8 bit for Blue and 8 bit for Alpha(transparency).

# Pixels indices:

Pixels are stored in an one-dimensional array, so you can't simply say `pixels[x][y]`.

As they are stored in order from left to right and from top to bottom, determining an individual pixel's index in the array is as simples as `pixels[x + (w * y)]` where `w`is the surface's width, and `x` , `y` are the coordinates.

I suggest defining a helper function for that:

```
int get_pixel_index(int x, int y, int w)
{
    return w * y + x;
}

```

# Getting individual pixels:

Accessing a single pixel by specifying it coordinates (x,y) in the surface can be achieved with the following code:

```
int index = get_pixel_index(x, y, Image->w);
Uint32 *all_pixels = (Uint32*) Image->pixels; //Get all pixels from surface.
Uint32 pixel = pixels[index]; //Get specific pixel

```

We use `Uint32` because we are reading from 32 bit surface.

### Reading pixel color information:

The `pixel` variable holds the color information for the requested pixel.

If you want to access the RGBA componnents indivudally you will need some bit twiddling or the SDL\_GetRBA function:

```
SDL_GetRGBA(pixel, Image->format, &red, &green, &blue, &alpha);

```

# Setting pixels:

You can set a pixel color as easily as:

```
pixel = color;

```

Where `color` is a Uint8 representing a RGBA color.

Alternatively, you can use SDL\_MapRGBA which let you specify color components individualy:

```
pixel = SDL_MapRGBA(Image->format, red, green, blue, alpha);

```

---
Tags: sdl, c, pixel
---


# Question
Title: "LNK2001: unresolved external symbol" when trying to build my program
I get the following error(s) on my program that captures the mouse and then draws a line. Errors:

```
1>------ Build started: Project: Capture_Mouse_Line, Configuration: Debug Win32 ------
1>  main.cpp
1>main.obj : error LNK2001: unresolved external symbol "public: static long * Line::yc2" (?yc2@Line@@2PAJA)
1>main.obj : error LNK2001: unresolved external symbol "public: static long * Line::xc2" (?xc2@Line@@2PAJA)
1>main.obj : error LNK2001: unresolved external symbol "public: static long * Line::yc1" (?yc1@Line@@2PAJA)
1>main.obj : error LNK2001: unresolved external symbol "public: static long * Line::xc1" (?xc1@Line@@2PAJA)
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>D:\Visual C++ Projects\Capture_Mouse_Line\Debug\Capture_Mouse_Line.exe : fatal error LNK1120: 5 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

```

Here is my code:

```
#include<allegro5\allegro.h>
#include<allegro5\allegro_native_dialog.h>
#include<allegro5\allegro_primitives.h>
#include<Windows.h>
#include<allegro5\allegro_windows.h>

#ifndef WIDTH
#define WIDTH 1440
#endif

#ifndef HEIGHT
#define HEIGHT 900
#endif

class Line
{
public:
    static void ErasePreviousLine();

    static void DrawLine(long* x, long* y,long* x2,long* y2);

    static bool Erasable();

static long* xc1;
static long* yc1;
static long* xc2;
static long* yc2;
};

 void Line::ErasePreviousLine()
{

    delete xc1;
    xc1 = NULL;
    delete yc1;
    yc1 = NULL;
    delete xc2;
    xc2 = NULL;
    delete yc2;
    yc2 = NULL;
 }

 bool Line::Erasable()
 {
     if(xc1 && yc1 && xc2 && yc2 == NULL)
     {
         return false;
     }
     else
     {
         return true;
     }
 }

 void Line::DrawLine(long* x,long* y,long* x2,long* y2)
 {

     if(!al_init_primitives_addon())
     {
         al_show_native_message_box(NULL,NULL,NULL,"failed to initialize allegro",
        NULL,NULL);
     }

     xc1 = x;
     yc1 = y;
     xc2 = x2;
     yc2 = y2;

     al_draw_line((float)*xc1, (float)*yc1, (float)*xc2, (float)*yc2,al_map_rgb(255,0,255), 1);

     delete x;
     delete y;
     delete x2;
     delete y2;
 }

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg;

    ALLEGRO_DISPLAY* display = NULL;

    if(!al_init())
    {
        al_show_native_message_box(NULL,NULL,NULL,"failed to initialize allegro",
        NULL,NULL);

        return -1;
    }

    display = al_create_display(WIDTH,HEIGHT);

    if(!display)
    {
        al_show_native_message_box(NULL,NULL,NULL,"failed to initialize display",
        NULL,NULL);

        return -1;
    }

    HWND hwnd = al_get_win_window_handle(display);

    if(hwnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while(GetMessage(&msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    static bool bIsCaptured;
    static POINTS ptsBegin;
    static POINTS ptsEnd;
    switch(msg)
    {
    case WM_LBUTTONDOWN:
        SetCapture(hwnd);
        bIsCaptured = true;
        ptsBegin = MAKEPOINTS(lParam);
        return 0;
    case WM_MOUSEMOVE:
        if(wParam & MK_LBUTTON)
        {
            if(!Line::Erasable())
            {
                return 0;
            }

            Line::ErasePreviousLine();

            ptsEnd = MAKEPOINTS(lParam);

            Line::DrawLine(new long(ptsBegin.x),new long(ptsBegin.y),new long(ptsEnd.x),new long(ptsEnd.y));
        }
        break;

    case WM_LBUTTONUP:
        bIsCaptured = false;
        ReleaseCapture();
        break;

    case WM_ACTIVATEAPP:
        {
            if(wParam == TRUE)
            {
                if(bIsCaptured){
                    SetCapture(hwnd);}
            }
        }
        break;
    }
    return 0;
}

```

# Answer
> 1 votes
You need to define the `static` variables explicit:

```
static long* xc1;
static long* yc1;
static long* xc2;
static long* yc2;

```

In the implementation file (.cpp), try adding this code:

```
long* Line::xc1 = NULL;
long* Line::yc1 = NULL;
long* Line::xc2 = NULL;
long* Line::yc2 = NULL;

```

More info at: http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

edit: I think the definition of the static members MUST be in the implementation file.

---
Tags: c++, geometry, allegro, win32
---


# Question
Title: matrix to transform unit cube to space defined by 8 arbitrary points
I asked a question relating to similar to this already, but I think this is a clearer objective of what Im trying to achieve.. or whether its possible at all!

Im trying to find a transformation (matrix ideally) which would transform the 8 points of a 3d unit cube to 8 arbitrary points in space.

The 8 target points have no known structure.

e.g:

My gut feeling is that a matrix is unable to provide this xform since the cube faces vertices can be concave.. but are there any other methods of transformation? Thanks!

# Answer
The transformation is non-linear, so you cannot use a conventional transformation matrix for it.

You could go with trilinear interpolation between all the `A0`, `A1`, `A2` etc. points. One way to compute it for an arbitrary point `P(x,y,z)` is:

```
f(P) = (1-z)*(1-y)*(1-x)*A0
     + (1-z)*(1-y)*  x  *A1
     + (1-z)*  y  *(1-x)*A2
     + (1-z)*  y  *  x  *A3
     +   z  *  y  *(1-x)*A4
     +   z  *  y  *  x  *A5
     +   z  *(1-y)*(1-x)*A6
     +   z  *(1-y)*  x  *A7

```

It can be rewritten as this simpler form:

```
f(P) = A0 + x*B1 + y*B2 + z*B3 + xy*C1 + yz*C2 + zx*C3 + xyz*D1

```

With the following precomputed constants:

```
A0
B1 =  A1-A0
B2 =  A2-A0
B3 =  A6-A0
C1 =  A3-A2-A1+A0
C2 = -A6+A4-A2+A0
C3 =  A7-A6-A1+A0
D1 = -A7+A6+A5-A4-A3+A2+A1-A0

```

Note that no matter how you perform the computation, you will need to store at least 24 constant floating point values to fully describe the transformation.
> 2 votes

# Answer
I have a gut feeling also, that

* The points have to close a convex area
* The points must be the corner points of the intersection of 6 planes.

Then, there may exist a matrix where

```
[a b c d ],  where (m+-a)x + (n+-b)y + (o+-c)z + (p+-d) == 0
[e f g h ]         (m+-e)x + (n+-f)y + (n+-f)z + (p+-h) == 0
[i j k l ]         (m+-i)x + (n+-j)y + (n+-k)z + (p+-l) == 0
[m n o p ]   are the equations of the 6 planes of the arbitrary shape

```

Then the matrix that transforms the cube to that shape is the inverse transform of the matrix == M^-1, as the forward matrix represents the transform from a viewing frustum to clip space (==unit cube). (Also we know that the frustum doesn't have to be symmetric, so there is quite a lot of degrees of freedom left...)
> 0 votes

---
Tags: 3d-meshes
---


# Question
Title: Game Physics: Implementing Normal Reaction from ground correctly
I am implementing a simple side scrolling platform game. I am using the following strategy while coding the physics:

* Gravity constantly acts on the character.
* When the character is touching the floor, a normal reaction is exerted by the floor.

I face the following problem:

If the character is initially at a height, he acquires velocity in the **-Y** direction. Thus, when he hits the floor, he falls through even though normal force is being exerted. I could fix this by setting the **Y** velocity to ***0***, and placing him above the floor if he has collided with it. But this often leads to the character getting stuck in the floor or bouncing around it. Is there a better approach ?

# Answer
Your first problem is that you do not want the floor to be exerting a literal force on the character. If you are using the term 'force' in its true sense, that means that it will change velocity over time, which is not what you want when your character hits the ground (or when any collision occurs, for that matter). What you are actually looking for is an *impulse*, or an immediate change in velocity.

For reference, I recommend some articles written by Chris Hecker.

Your proposed fix of setting the y-velocity to 0 and adjusting the position above the ground is certainly a valid solution, since that would be an implementation of an impulse. For the general case (referring to Hecker's articles) you would multiply by the coefficient of restitution to calculate the new y-velocity. The problems you are describing indicate that there might be something else wrong with your code.

The other problem you might be facing is the contact problem: when one body is only contacting another, and not actually colliding or intersecting with it. The biggest problems arise when stacking objects on top of each other. This is actually difficult to solve, but alternate timestep schemes such as the one proposed in this paper open the door for solutions. I'm afraid I may be going on the scope of the question though so I'll stop there...

To sum up, I think you have the correct fix, and there is another bug in your code. It could be the order in which you carry out the collision response operations.
> 3 votes

---
Tags: physics, platformer, side-scroller
---


# Question
Title: Android/Java AI agent framework/middleware
I am looking for an AI agent framework to use as a starting point in an Android game I have to create for a university research project. It has been suggested to me to use JADE, but, as far as I can tell, it's not a suitable framework for games (at least for my game idea) because it runs in a split-execution mode, and it needs an always-active network connection to a main host.

What I want is just a little something to give me a headstart. I am willing to adjust the game's features to the framework because it's more of a mockup game, and the purpose is to compare the performance of a couple of agents in the game world. The game will be very simplistic, with a minimal UI that displays various stats about the characters in the game (so no graphics, no pathfinding).

Thank you.

# Answer
I may be dating myself here a bit but I've had the best results with Jade for multi-agent systems.

http://jade.tilab.com/

They also seem to be focusing on Android in recent years. There is quite a bit on documentation including a book that had be jumpstarted in just a few hours: Deploying multi-agent systems with JADE

One last thought: though FIPA is now replaced by IEEE I always gravitate toward standards compliant frameworks, like Jade, where possible. This gives at least some measure of confidence that the framework will continue to be useful into the future.

Good luck with your project.
> 2 votes

# Answer
I'm using JaCa-Android myself for a university project, though it's not for a game. After researching a plethora of mobile agent frameworks, it appears to be the most suitable for an Android device, since it integrates very smoothly and can run a middleware app to access all the Android system features (like notifications and sensors). The Jason language is an extension of AgentSpeak which itself is very Prolog-like, and the agents can easily call methods of Java objects in the environment.

No doubt this is too late to answer your question, but for future reference, I've had good experiences with it so far.
> 1 votes

---
Tags: java, android, ai
---


# Question
Title: Player rewards in games where you normally have nothing to purchase
In many games there are rewards such as gold coins, points, etc. When these rewards can be used to purchase in-game items, it motivates the player to keep playing.

Let's say we have an online game, poker, Yatzy etc. What type of reward would keep the players playing if there are few in-game items available to buy, or none at all?

What I am looking for is a reward system that entices the players to play more in a game environment where there isn't that much to purchase. For example, there isn't much to buy in a poker or Yatzy game with the gold you win.

I guess having some titles that are added to the `userid` is one way, or maybe purchasing a logo for the id... A leaderboard is another.

Any thoughts on this?

# Answer
> 6 votes
There was a poker game - Governor of Poker \- where you were making money to buy out whole Texas (I may exaggerate here), that was a funny idea, because it was giving you **an objective**.

Another thing that poker reminds me is **strip poker**! That's a great way to motivate players - not only in poker, stripping girls are welcomed everywhere (well, maybe not on a minigame made for a site about feminism). Just remember to comment this answer with link to your game when it's finished, so I don't miss it.

Some people simply implement **score**. It's especially nice if you can share it with others, and you will rather want to share "Yeaster Master" in a beer promotion game than "1539205", so coming up with **funny rank names** may pay off.

Similarly to above, a lot of games nowadays spend time on creating **achievements**, especially if you can share them on your blog, **Facebook**, **forum signature** etc.

Also a great reward for a player is **new content unblocked** \- usually it's just a step forward in story of a RPG game, though it works also with lesser rewards in low budget games, like unblocking Hold'em variant in a poker game.

If you have other products, you can put some **secret code** for another game. Hackers won't take it from decompiled code, because they won't know it exists.

Edit: Krom Stern pointed out in comment section, it might be helpful to put more examples about the \>\>content unblocking\<\<. He's right, that the term "content" is vague, as it should be. Basically anything is content: soundtrack, background, model textures and game mechanics. If you, a player, a modder or a random generator create something - it's content. It may be counter-intuitive what kind of content may be a good reward. Some developers think only a content involved in game mechanics will meet player's satisfaction: a trinket increasing luck, an hourglass able to rewind some unfortunate events (drawing bad cards) etc. However, there are a number of "unlockables" invented by designers throughout the gaming history. Here are some relevant to a card game example supplied by question's author:

* Codex - a book with trivia, where some facts (or parts of fictional story) are revealed,
* Avatars - very rewarding if a forum or chat is connected with the game,
* Card backs, as practiced by Blizzard in Hearthstone,
* Similarly as above, alternative front look of cards could be a reward,
* Different table, token, player avatars (as in heads near the table, representing the players) textures
* Steam, Kongregate and other badges etc.

If you run out of things (or rather categories of things) to unlock, then you can also add another layer to the game, as in the game mentioned in first paragraph. For example, you could have a living room with space for various vanity items that represent your wealth in a more rewarding manner than a number.

# Answer
> 5 votes
**Achievements** (wiki). Now they are everywhere: in MMOs, Online games, even Visual Studio has extensions with achievements system. Even StackOverflow has it! =) \[Kill 1000 rabits\], \[Win 20 poker games in a in a row\], \[Come online every day for 1 year\], \[Write over 9000 stupid answers\]... They are just a pop up shiny boxes or a table in a player profile, but players just play achievements. Not sure why. You can add ranking table on a main page. Also you can make achievement points as base for another awards: titles, special avatars, badges as said Markus von Broady.

# Answer
> 3 votes
Essentially, if you are not acquiring in game merchandise using the credits you earn, the only motivation for earning them is status. The game should create an environment in which the player wishes to be the wealthiest. Try to set up leaderboards, or in some way allow the players to convey their achievement, that way they want to have more than everyone else.

---
Tags: game-design
---


# Question
Title: How a "Collision System" should be implemented?
My game is written using a entity system approach using Artemis Framework. Right know my collision detection is called from the *Movement System* but i'm wondering if it's a proper way to do collision detection using such an approach.

Right know i'm thinking of a new system dedicated to collision detection that would proceed all the *solid* entities to check if they are in collision with another one.

I'm wondering if it's a correct way to handle collision detection with an entity system approach? Also, how should i implement this *collision system*?

I though of an `IntervalEntitySystem` that would check every 200ms (this value is chosen regarding the Artemis documentation) if some entities are colliding.

```
protected void processEntities(ImmutableBag<Entity> ib) {
    for (int i = 0; i < ib.size(); i++) {
        Entity e = ib.get(i);
        //check of collision with other entities here
     }
}

```

# Answer
> 2 votes
Ideally, `MovementSystem` should process movement only, and there should be a separate system for collision detection/reaction. The only benefit I see from processing collisions in the movement system is that you could use the same loop that processes movement to process collisions, so it would be more efficient.
But unless your game had performance issues due to logic updates taking too long, I would move collision detection/reaction to a separate `CollisionSystem` which is processed after `MovementSystem`. This would be a cleaner solution in my opinion.

And, about your last question, I would check for collisions each frame. Checking every 200ms can lead to entities colliding without being detected in some cases.
This might depend on the kind of game that you're making, the speed your entities are moving at, your game update frame rate...

**EDIT:** In response to this question:

> Also i'm wondering what the movement system should do regarding this approach. ATM, my movement system look at the Velocity component of all the concerned entities and do a simple translation of the entity coordinates but since the collision calculations are made in another system, i would need to know the "old" and move the entity to his hold position in case of collision. I'm not really fan of this. – nathan

The movement system should update the current position of each entity, just as you describe.
When you react to collisions it isn't necesary to know the last position of each entity. If you don't want an entity to break through another one, you could calculate the projection vector of the overlap and use it to resolve the collision. This article explains very well how to detect simple collisions and how to calculate the projection vector using the Separating Axis Theorem (SAT).

---
Tags: java, collision-detection, entity-system, slick, artemis
---


title: Camera not working

text:
# Question
Title: Camera not working
I made a camera in DX9. To move forward I press the Up arrow. To rotate on the Y axis I use the mouse. When I perform these movements on their own the camera moves at the speed I want.

However, if I hold down Up and move the mouse at the same time then the camera moves a lot faster than it should. I want it to move at the same speed as it does when only the Up arrow is pressed.

I think I need to normalize something somewhere but not sure what and not sure where. Have tried various combinations without success so if anyone can point me in the right direction that would be great.

Thanks.

### My code

```
#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)

LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    if( KEY_DOWN(VK_UP))    MovePlayer(D3DXVECTOR3(0, 0, -1.0f));
    if( KEY_DOWN(VK_DOWN))  MovePlayer(D3DXVECTOR3(0, 0, 1.0f));

    switch( msg )
    {
        case WM_MOUSEMOVE:
        ProcessMouseInput();
    }
}

void  MovePlayer( D3DXVECTOR3 in_vec )
{
    D3DXMATRIX CameraRot;
    D3DXMatrixRotationY(&CameraRot,D3DXToRadian(AngleY));
    D3DXVECTOR3 CameraRotTarget;
    D3DXVec3TransformNormal(&CameraRotTarget,&in_vec,&CameraRot);
    CameraPos +=  (m_timeElapsed * CameraRotTarget);
}

void ProcessMouseInput()
{
    GetCursorPos( &CurrentMouseState );

    if ((CurrentMouseState.x != GameMouseState.x) || (CurrentMouseState.y != GameMouseState.y))
    {
        int dx = CurrentMouseState.x - GameMouseState.x;
        int dy = CurrentMouseState.y - GameMouseState.y;
        AngleY+=m_timeElapsed*dx*7.0f;
    }
    GameMouseState = CurrentMouseState;
    // Set back to window center in Render function
}

VOID UpdateCamera()
{
    D3DXVECTOR3 CameraOrigTarget(0, 0, -1);
    D3DXVECTOR3 CameraOrigUp(0, 1, 0);

    D3DXMATRIX CameraRot;
    D3DXMATRIX CameraRotX;
    D3DXMatrixRotationX(&CameraRotX,D3DXToRadian(AngleX));
    D3DXMATRIX CameraRotY;
    D3DXMatrixRotationY(&CameraRotY,D3DXToRadian(AngleY));
    CameraRot = CameraRotX * CameraRotY;
    D3DXVECTOR3 CameraRotTarget;
    D3DXVec3TransformNormal(&CameraRotTarget,&CameraOrigTarget,&CameraRot);

    D3DXVECTOR3 CameraTarget;
    CameraTarget = CameraPos + CameraRotTarget;

    D3DXVECTOR3 vUpVec( 0.0f, 1.0f, 0.0f );
    D3DXMatrixLookAtLH( &matView, &CameraPos, &CameraTarget, &vUpVec );
    g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

    D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI / 4, 1.0f, 1.0f, 100.0f );
    g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
}

```

# Answer
> 3 votes
> You're moving the camera twice, one for the mouse and one for the keyboard. The solution's to set a flag (b\_moveUp, for example) in ProcessInput, and in your UpdateCamera "consume" it: if it's set move properly and then reset the flag.

Ok, let's do this properly.

**The problem**:
The movement's bound to the MsgProc function. You can't control the amount of windows messages you receive, so your speed depends on the user moving the mouse (and its resolution), the character repeat rate, and other foreign events. In order to fix this, we need to isolate these two different issues: **detecting user input** and **applying the required movement**.

**A possible solution**:
We need a way to transfer the input state to the update loop. We can do it like this:

```
// On MsgProc...
if( KEY_DOWN(VK_UP)) {
    m_controller.moveForward();
}
if( KEY_DOWN(VK_DOWN)) {
    m_controller.moveBackward();
}

// On update function...
m_controller.apply(m_timeElapsed);

// And this might be the implementation of the controller
class Controller {
public:
    void moveForward() {
        _directionFlags[Direction::FORWARD] = true;
    }

    void moveBackward() {
        _directionFlags[Direction::BACKWARD] = true;
    }

    void apply(float elapsed) {
        Vector3 offset {0, 0, 0};
        for (auto &flag : _directionFlags) {
            if (flag.second) { // If flag is set...
                offset += _offsets.at(flag.first); // Add the movement's offset.
                flag.second = false; // Reset the flag.
            }
        }
        offset *= elapsed;
        // TODO: Transform offset by rotations...
        // TODO: Apply offset to target entity...
    }
private:

    enum class Direction {
        FORWARD,
        BACKWARD
    };
    typedef std::map<Direction, bool> DirectionFlags;
    DirectionFlags _directionFlags;
    typedef std::map<Direction, Vector3> Offsets;
    const static Offsets _offsets;
};

const Controller::Offsets Controller::_offsets = {
    {Direction::FORWARD, {0, 0, -1.0f}},
    {Direction::BACKWARD, {0, 0, 1.0f}}
};

```

---
Tags: c++, 3d, mathematics, directx, camera
---


title: knowing all available entity types

text:
# Question
Title: knowing all available entity types
I'm making a game where at some point the game will create enemies of random types. Each type of enemy available is defined on its own class derived from an enemy superclass. To do this, obviously the different types of enemies should be known. This is what I have thought of:

1. Just make a list manually. Very simple to do, but I don't like it because I'll be adding more enemy types over time, so any time I add a new class I have to remember to update this (same if I remove an enemy). I would like some kind of auto-updating list.
2. A completely component based system. There are no different classes for each enemy, but definitions of enemies in some file where all enemy types can be found. I really don't need that level of complexity for my game. I'm still using a component based model to some degree, but each Enemy type gets defined on its own class.
3. Java Annotation processing. Give each enemy subclass an annotation like @EnemyType("whatever"), then code an annotation processor that writes in a file all available enemy types. Any time a new class is added the file gets updated after compilation.This gives me a feeling of failure even if its a good solution, it's very dependant on Java, so it means I cant think of a general design good for any kind of language. Also I think that this would be too much work for something so simple.

I would like to see comments on these ideas and other possible solutions

Thanks

# Answer
> 6 votes
Why don't you use 1 & 2?

I think what you're looking for is a Factory with a createRandom method, and you can then register functions/classes from a definition file/data, you still have to remember to update the file but at least it won't need a recompile.

If your problem is remembering to update the factory then a possible solution would be that the enemy class auto-registers it self to the factory and then all your subclasses will have that behavior. This seems to fix all the problems stated in 1.

# Answer
> 2 votes
You seem to be using Java. If so, use its reflection and just scan all classes in your creature package.

---
Tags: architecture
---


title: samplerCubeShadow and texture offset

text:
# Question
Title: samplerCubeShadow and texture offset
I use sampler2DShadow when accessing a single shadow map. I create PCF in this way:

```
result += textureProjOffset(ShadowSampler, ShadowCoord, ivec2(-1,-1));
result += textureProjOffset(ShadowSampler, ShadowCoord, ivec2(-1,1));
result += textureProjOffset(ShadowSampler, ShadowCoord, ivec2(1,1));
result += textureProjOffset(ShadowSampler, ShadowCoord, ivec2(1,-1));
result = result * 0.25;

```

For a cube map I use samplerCubeShadow:

```
result = texture(ShadowCubeSampler, vec4(normalize(position), depth));

```

How to adopt above PCF when accessing a cube map ?

# Answer
If you're looking for soft shadows, then you have to go back to the reason why shadows aren't hard in the real world.

Soft shadows are a by-product of lights that have a finite area. In order to handle this properly, you have to actually check how much of a light source is visible; it's not just a binary on/off.

Your 4x4 kernel is a good approximation for soft shadows, but only for directional lights. Each sample is effectively approximating a light of a particular apparent size. And since directional lights are infinitely far away, all objects will see the same apparent size of the light. So a fixed, 4x4 kernel can approximate soft shadows for a particular area of the light.

For a *point light*, that approximation no longer makes sense. You can't use a *fixed* kernel to get soft shadows, because the apparent size of the point light changes depending on where you are.

For this, you need to compute the apparent area of the light (based on the light's size), then compute a number of directions within this area which you feel is representative of the area. Or just whatever you feel you can get away with without killing your performance. You use these directions as the normals in your shadow tests. Done.

Now all of this is an approximation (or really just a hack), because they don't really provide soft shadows at all. The problem with these approximations is that they're basically changing the place in the world that they're looking for shadows from, rather than changing the place on the light where they're looking for shadows from. For a directional light, it's really one and the same, but not so for a point light. To get soft shadowing more accurately for point lights, you would need to render multiple shadow maps from multiple different positions.

Or just go with the approximation; it's probably loads cheaper.
> 3 votes

---
Tags: opengl, glsl, shadow-mapping
---


# Question
Title: Should components have sub-components in a component-based system like Artemis?
I am designing a game using Artemis, although this is more of philosophical question about component-based design in general. Let's say I have non-primitive data which applies to a given component (a Component "animal" may have qualities such as "teeth" or "diet"). There are three ways to approach this in data-driven design, as I see it:

1) Generate classes for these qualities using "traditional" OOP. I imagine this has negative implications for performance, as systems then must be made aware of these qualities in order to process them. It also seems counter to the overall philosophy of data-driven design.

2) Include these qualities as sub-components. This seems off, in that we are now confusing the role of components with that of entities. Moreover out of the box Artemis isn't capable of mapping these subcomponents onto their parent components.

3) Add "teeth", "diet", etc. as components to the overall entity *alongside* "animal". While this feels odd hierarchically, it may simply be a peculiarity of component-based systems.

I suspect 3 is the correct way to think about things, but I was curious about other ideas.

# Answer
The combination of components is what makes the entity. Giving entities certain components just so they can be categorized does not seem very useful. For example, consider two entities: A bear and a horse. They're both going to have pretty much identical components, just the data the components contain is going to differentiate them. A simple example would be:

```
            Horse           |  Bear
Component
Position:   10,32           |  10, 43
Health:     100/100         |  243/300
Attack:     Hooves          | Claws,Teeth
Sprite:     Horse.png       | Bear.png
Diet:       Hay             | Horse meat
Info:       Horse, rideable | Bear, run.

```

As you can see, they have identical components. However, the components have different data. You could expand on the information component, but it's likely going to contain common information for all the entities of that type. So it's probably better to just have it stored someone common and just have a reference to it in the component.

I would recommend keeping your components more general and use a different data structure for querying your entities, something outside of your entity framework. When you create an entity you can store its ID in a table for that type of animal. Then when you want to look up all the animals with teeth, you only need refer to your table and you'll get all the entity IDs that have that attribute.

Alternatively, Artemis has a tag system for entities you could utilize. Which is essentially what's described above. It allows you to add tags to entities and query all the entities that have those tags. Though, last time I looked at the source it wasn't implemented. So you may have to implement something yourself.
> 7 votes

---
Tags: architecture, component-based, artemis
---


title: Detecting long held keys on keyboard

text:
# Question
Title: Detecting long held keys on keyboard
I just want to ask if can I check for "KEY"(keyboard) that is HOLD/PRESSED for a long time, because I am to create a clone of breakout with air hockey for 2 different human players. Here's the list of my concern:

1. Do I need other/ 3rd party library for KEY HOLDS?
2. Is multi-threading needed? I don't know anything about this multi-threading stuff and I don't think about using one(I'm just a NEWBIE).
3. One more thing, what if the two players pressed their respective key at the same time, how can I program to avoid error or worse one player's key is prioritized first before the the key of the other. example:

Player 1 = W for UP & S for DOWN Player 2 = O for UP & L for DOWN

(example: W & L is pressed at the same time)

PS: I use GLUT for the visuals of the game.

# Answer
> 7 votes
You do not need a 3rd party library or multi-threading to detect long held keys. Depending on how you're doing it now, you're either going to be polling the keyboard to see what keys have been pressed or you're going to be responding to events when keys are pressed.

Either way, you're going to have a variable that keeps track of the exact time the key was pressed. Then, in your game loop you can see how long the key has been held just by checking `currentTime - keyPressedTime`. The difference will give you how long the key has been held.

Finally, while it's unlikely that players would press their keys at the exact same frame, this is possible if you're running slow or by chance. You can pick which player to process first by random choice. Simply generate a number of some `MaxValue` and if it's less than `MaxValue/2` process player 1, otherwise process player 2.

# Answer
> 4 votes
Not sure it is perfect or exaсtly what you looking for and its for single-player, but try something like that (adapted from some books for newbies):

```
bool m_bPressedKeys[256];  // array of pressed keys current frame
bool m_bPressedKeysPrev[256]; // previous frame
bool m_bKeyLock[256];
float m_KeyDelayTimer(0.25f);
    float m_KeyRepeatTimer(0.01f);
GetINput()
{
    UCHAR pKeyBuffer[ 256 ];
    ZeroMemory( pKeyBuffer, sizeof( UCHAR ) * 256 );
    GetKeyboardState(pKeyBuffer); // Change this for non-Windows platforms
    memcpy(&m_bPressedKeysPrev, &m_bPressedKeys, sizeof(bool)*256);
    if (!(pKeyBuffer[i] & 0xF0))
    {
        m_bKeyLock[i] = false;
        m_bPressedKeys[i] = false;
    }
    else
    {
        m_bPressedKeys[i] = !(m_bKeyLock[i]);
    }
}

// You can use arrays OR accessors like this
bool KeyDown(const unsigned int& key)   const   { return ( m_bPressedKeys[key])&&(!m_bPressedKeysPrev[key]); }
bool KeyStillDown(const unsigned int& key) const { return ( m_bPressedKeys[key])&&( m_bPressedKeysPrev[key]); }
bool KeyUp(const unsigned int& key) const       { return (!m_bPressedKeys[key])&&( m_bPressedKeysPrev[key]); }
bool KeyStillUp(const unsigned int& key) const  { return (!m_bPressedKeys[key])&&(!m_bPressedKeysPrev[key]); }

// OR something more complicated:
bool IsKeyPressed( const int& key ) // returns true only once per press
{
    if ( KeyDown(key) )  // Simple check
    {
    LockKey(key); // Prevent key from pressing next frames until released
    return true;
    }
return false;
}

bool IsKeyPressedRepeatable( const int& key, const float& dt )
// "Tetris-style moving"
// returns true once, then after `KeyDelayTimer` seconds and repeats
// every `KeyDelayInterval` seconds (or your time units).
// dt - is a delta time between game frames
{
if (KeyStillDown(key))
{
    m_KeyDelayTimer += dt;
    if (m_KeyDelayTimer >= m_KeyDelayInterval)
    {
        m_KeyRepeatTimer += dt;
        if ( m_KeyRepeatTimer >= m_KeyRepeatInterval )
        {
            m_KeyRepeatTimer -= m_KeyRepeatInterval;
            return true;
        }
    }

}
if (KeyDown(key))
{
    return true;
}
if (KeyUp(key))
{
    m_KeyDelayTimer = 0.0f;
}
return false;
}

```

Usage example:

```
if ( m_bPressedKeys['w'] ) // Just move player continuously every frame while key is pressed
{
    m_Player.Move( m_Player.GetSpeed() * dt, 0 ); // dx, dy
}

if ( m_bPressedKeys[VK_ESCAPE] ) // Go to menu once per press
{
    LockKey( VK_ESCAPE );
    m_Game->ChangeState(MenuState);
}

if ( IsKeyPressedOnce(VK_Space)) // Jump once per Spacebar press
{                                // Same as above, but cleaner
    m_Player->Jump();
}

if ( IsKeyPressedRepeatable(VK_LEFT, dt) ) // Move figure in Tetris.
{                                          // Second tick is delayed and
    m_Tetris->MoveFigureLeft();            // then repeating discretely
}

```

AFAIK not all keyboards supports multiple key presses at once or implement it not quite correctly. You must dig into it before coding.

# Answer
> 0 votes
Just use a timer. Have a Boolean that starts at false then when a key is pressed it makes it true. But also have when the key is not being pressed the Boolean is false. So when the timer reaches a certain number of milliseconds/time then have it do what you want... Hope this helps! :)

# Answer
> 0 votes
1. You do not need a 3rd party library. You just need to be able to know if a key is held down or not.
2. No multithreading is needed. Some libraries may use threading behind the scenes, but you do not have to create any threads for this.
3. I don't believe you have much control over that.

Basically what you need to do is store the state of every key (held down or not), perhaps in an array. Every time you perform your update, record the current state if each key. Each key needs not just a Boolean of whether or not it is held down, but rather a positive number indicating how many successive frames that the key has been held (0 meaning the key is not held). By doing this, you can check to see how many frames a key has been held down, and customize your input to your liking. For example, you could only fire an action if a key press has a value of 1, and now that action will only fire the first time you press a key. Or fire an action whenever a key press value is greater then 0, meaning the action will be performed every update as long as the key is held down. You could even only perform an action after a key has been held for 10 frames. The feel of the input is up to you.

---
Tags: c++, 2d, algorithm, game-mechanics
---


# Question
Title: "Marching cubes" voxel terrain - triplanar texturing with depth?
I am currently working on a voxel terrain that uses the marching cubes algorithm for polygonizing the scalar field of voxels. I am using a triplanar texturing shader for texturing. say I have a grass texture set to the Y axis and a dirt texture for both the X and Z axes. Now, when my player digs downwards, it still appears as grass. How would I make it to appear as dirt? I have been thinking about this for a while, and the only thing I can think of to make this effect, would be to mark vertices that have been dug with a certain vertex color. When it has that vertex color, the shader would apply that dirt texture to the vertices marked. Is there a better method?

# Answer
Yep, that's what Ken Silverman's VoxLap Engine did; by today's standard's you're typically better off (re)calculating voxel data as and when you need it, than consuming memory by pregenerating things you don't need *right now*. Although the data structure used was RLE, each voxel was in essence "born equal". It was only when something was exposed (i.e. when it became a surface voxel) that it had to be assigned a new colour... given the limitations at that time, I've little doubt this also reduced the size of the active surface voxel set and so enormously reduced memory consumption which was at a premium.

...Though Silverman's was a "pure" RLE voxel engine as found in the NovaLogic games, not the expensive, polygon driven kind we see everywhere today. But many of the same challenges apply... like this one.
> 1 votes

# Answer
off the top of my head, I can think of a few possible solutions;

My implementation assigns a colour to each vertex, and can blend between 4 different sets of tri-planar maps. Each voxel has a material type, and I blend the colours based on that.

In your case I could use one material as dirt with grass, and one as plain dirt. When generating my voxels I could to a surface check to see if dirt is exposed, and set it to grass-dirt.

Digging would produce dirt surface.

This also allows you to have other material types - trivially 4 material types, but with a little work, you can extend that further too.

Or, perhaps create a top-down projection map, and use localized splat mapping.
> 1 votes

---
Tags: procedural-generation, voxels, terrain-rendering, marching-cubes, triplanar-texturing
---


# Question
Title: Why is this beat detection code failing to register some beats properly?
I made this SoundAnalyzer class to detect beats in songs:

```
class SoundAnalyzer
{
    public SoundBuffer soundData;
    public Sound sound;
    public List<double> beatMarkers = new List<double>();

    public SoundAnalyzer(string path)
    {
        soundData = new SoundBuffer(path);
        sound = new Sound(soundData);
    }

    // C = threshold, N = size of history buffer / 1024  B = bands
    public void PlaceBeatMarkers(float C, int N, int B)
    {
        List<double>[] instantEnergyList = new List<double>[B];
        GetEnergyList(B, ref instantEnergyList);
        for (int i = 0; i < B; i++)
        {
            PlaceMarkers(instantEnergyList[i], N, C);
        }
        beatMarkers.Sort();
    }

    private short[] getRange(int begin, int end, short[] array)
    {
        short[] result = new short[end - begin];
        for (int i = 0; i < end - begin; i++)
        {
            result[i] = array[begin + i];
        }
        return result;
    }

    // get a array of with a list of energy for each band
    private void GetEnergyList(int B, ref List<double>[] instantEnergyList)
    {
        for (int i = 0; i < B; i++)
        {
            instantEnergyList[i] = new List<double>();
        }
        short[] samples = soundData.Samples;

        float timePerSample = 1 / (float)soundData.SampleRate;
        int sampleIndex = 0;
        int nextSamples = 1024;
        int samplesPerBand = nextSamples / B;

        // for the whole song
        while (sampleIndex + nextSamples < samples.Length)
        {
            complex[] FFT = FastFourier.Calculate(getRange(sampleIndex, nextSamples + sampleIndex, samples));
            // foreach band
            for (int i = 0; i < B; i++)
            {
                double energy = 0;
                for (int j = 0; j < samplesPerBand; j++)
                    energy += FFT[i * samplesPerBand + j].GetMagnitude();

                energy /= samplesPerBand;
                instantEnergyList[i].Add(energy);

            }

            if (sampleIndex + nextSamples >= samples.Length)
                nextSamples = samples.Length - sampleIndex - 1;
            sampleIndex += nextSamples;
            samplesPerBand = nextSamples / B;
        }
    }

    // place the actual markers
    private void PlaceMarkers(List<double> instantEnergyList, int N, float C)
    {
        double timePerSample = 1 / (double)soundData.SampleRate;
        int index = N;
        int numInBuffer = index;
        double historyBuffer = 0;

        //Fill the history buffer with n * instant energy
        for (int i = 0; i < index; i++)
        {
            historyBuffer += instantEnergyList[i];
        }

        // If instantEnergy / samples in buffer < instantEnergy for the next sample then add beatmarker.
        while (index + 1 < instantEnergyList.Count)
        {
            if(instantEnergyList[index + 1] > (historyBuffer / numInBuffer) * C)
                beatMarkers.Add((index + 1) * 1024 * timePerSample);
            historyBuffer -= instantEnergyList[index - numInBuffer];
            historyBuffer += instantEnergyList[index + 1];
            index++;
        }
    }
}

```

For some reason it's only detecting beats from 637 sec to around 641 sec, and I have no idea why. I know the beats are being inserted from multiple bands since I am finding duplicates, and it seems that it's assigning a beat to each instant energy value in between those values.

It's modeled after this: http://www.flipcode.com/misc/BeatDetectionAlgorithms.pdf

So why won't the beats register properly?

# Answer
I took a stab at it, which was dumb because I not familiar with Fourier transforms or music theory. So, after some study I don't have a solution, but I see several troubling things:

* The code for the Sound and Soundbuffer is missing and could be easily be the culprit
* The Fourier Transforms
    + I couldn't find the same Fourier transforms library by googling the namespace and method names, which means that code might be custom and could be the source of the problem
    + The fact that FastFourier.Calculate takes an array of short is unusual
* The method GetEnergyList takes a ref List but this list isn't used again?
* In several spots you see the SampleSize hard coded to 1024, but it isn't clear that is always the case.
* It is troubling that the comment for PlaceBeatMarkers notes that N should be divided by 1024, maybe the calling code forgot to do that?
* I'm very suspicious of the way historyBuffer is manipulated in PlaceMarkers, especially since N is passed in and then used to manipulate the historyBuffer.
* The comment `*// Fill the history buffer with n * instant energy*` and the code that follows doesn't jive.

After a while I just got the feeling the code isn't really organized well and it'd be a waste of time trying to fix. If you think it is worth it, the next step I'd take is:

1. Break it down to the most simplest part
2. Rewrite the code in the most verbose way, name all the hidden variables
3. Write unit tests to make sure that little part of code works correctly
4. Add another small section of code and repeat until you've got the whole thing working right

**Tips**

* You might want to make the number of bands fixed to simplify the loop logic
* Give variable like N, C and B good names that are clear and concise, this will help you mind see logical errors easier
* Break big sections of code into several called methods that each do a small concise step of the bigger process and can have unit tests written to ensure it is working correctly.
> 7 votes

---
Tags: c#, audio
---


title: Hit Detection When rotating the camera

text:
# Question
Title: Hit Detection When rotating the camera
This bug/feature has been plaguing me for a while and i want to know the best way to fix it. I'm testing simple hit detection with a wall, like:

```
 if (Forward button)
        if(Inv.w.z < -49 || Inv.w.z > 49)
            pos.z = 0.0f;
        else if(Inv.w.x < -49 || Inv.w.x > 49)
            pos.z = 0.0f;
        else
            pos.z = +1.0f;

```

where Inv.w. is the camera positions. Now obviously when i now hit that certain point i can no longer move away from the wall or anywhere in fact. How can i change this code to allow for the camera to be turned away from the wall so therefore i should be allowed to move?

for example, the player hits the wall and i cant move until i turn around or to the side?

I know its something to do with velocity but im pretty new to this so please bare with me if this is easy.

# Answer
Try adding the direction vector to the check. What you really do then is to check where you are going the next frame, and if there is no collision then you can simply move the camera. Otherwise, you don't move the camera, and therefore you won't get stuck!

See it like this:

You are one of those Warhammer table figures, and you have a ruler pointing in the direction you're going to travel. You just place that in front of you every frame, and if that ruler is intersecting anything, you know you can't move there - and therefore don't move the extra length that the ruler holds

```
Position + ( direction * speed );

```

***SPEED*** in this case is how far you want to move every frame, since ***DIRECTION*** is normalized (or you should be using a normalized vector)
> 1 votes

---
Tags: c++, collision-detection
---


# Question
Title: Is there a multiplayer game engine where you can write the logic in any programming language?
I'm working on a mud (multiplayer text game) engine and I would like developers to be able to write their game logic in any programming language. Does anyone know if other engines like this exist?

# Answer
> 6 votes
MUDs typically have a text interface accessible via a simple TCP stream.

Developers who wish to write game logic in arbitrary languages could simply have their programs interface with the MUD back-end via that text interface. Let them log into pseudo-characters and send text commands to the back-end, and receive results across that existing interface.

This approach would work for any language which supports opening a TCP network connection, and the engine then doesn't have to care at all about what language individual developers use, since it's interacting with them across a generic text interface.

# Answer
> 3 votes
There is - and can't be - a system which accepts *any* language. After all, to achieve that goal, *somebody* would have to add compilers or interpreters for languages like Piet or Befunge. While this is certainly possible for any given language, it's not possible for all of them - while you're implementing them, somebody will just invent a bunch of new ones.

That said, there are common virtual machines which already have compilers for a lot of languages each. All you have to do is to build the engine around those VMs. The three most commonly encountered are:

* LLVM (C, C++, Ada, Fortran, D, Objective-C, Haskell, ...)
* JVM (Java, Erjang, Rhino, Quercus, Jython, NetRexx, JRuby, Jacl, ...)
* CLR (C#, VB.Net, F#, J#, Axum, A#, Boo, Cobra, M, Oxygene, IronScheme, IronPython, IronRuby, Phalanger, P#, Scala, ...)

# Answer
> 1 votes
Short answer: No there is no mud-engine that accepts any language.

There is probably nothing at all that accepts 'ALL' languages (except for the keyboard and still I'm not sure).

That said, I'd suggest that you make the core (the engine) in whatever language you want and then offer bindings to the most common languages used, for example:

* Lua
* Python
* Java
* javascript
* C/C++

Those are either scripting languages with big communities around them or languages that are used by a lot of programmers.

I'd just go for Lua though (or another well known scripting language) for starters and add other ones as per request when the API and the engine is ready.

---
Tags: mud
---


# Question
Title: Can I create a Star Wars game without infringing copyright?
> **Possible Duplicate:**
> Legal issues for a “fangame” of a commercial franchise?

Is it possible to create my own commercial game based on the Star Wars Universe, without any copyright infringement?

# Answer
> 3 votes
It is possible, but you can't use Star Wars or any other trademarked names, nor any content from existing games (graphics, sound, etc.) in your game. So, essentially, while possible, it will be a challenge to save the Universe spirit. And anyway, for any such serious attempts (like if your money is involved) you should consult a lawyer.

# Answer
> 2 votes
It's primarily a trademark issue. You wouldn't be able to do this without trademark infringement (and also, probably copyright infringement).

---
Tags: game-industry, copyright
---


title: How do I create a selection rectangle?

text:
# Question
Title: How do I create a selection rectangle?
I have a basic prototype working with health, resources and units. The problem is: How do I select multiple units? I have an idea of making an rectangle which dynamically extends with the mouse position. I think I need to convert this rectangle to transparent rectangle.

# Answer
pygame.draw.rect should be enough to draw transparent rectangles, according to documentation if you use width \> 0, then the rectangle won't be filled.
> 3 votes

---
Tags: python, pygame, rts
---


# Question
Title: Exporting an animated FBX to XNA? (in 3DS Max)
I'm now working on an XNA 3D game, and I want to add animated models in it. I came across this example. I see there is one FBX file and a few texture files in the content project, and that in the code you can choose which "take" to play. In this code it is "Take\_001". Please tell me: When I create and animate my own 3D model in 3DS Max (2012, since I was told it's only possible in this version), how can I define those takes? plus, are any configurations need to be made when exporting FBX from 3DS Max to XNA?

Thank you.

# Answer
> 1 votes
I actually got it working. Although, I ended up using Blender. I created a bone system for the model, textured it, animated it and when exporting there's an "XNA Strict Options" check mark. I checked it, unchecked it, and then checked "Export Default Take". and it works :)

# Answer
> 3 votes
if you still want to use 3DS Max for your animation takes you can use this:

http://www.turbosquid.com/FullPreview/Index.cfm/ID/701878

# Answer
> 1 votes
Animation in XNA is the one and only reason I did not pursue a game solution in XNA, the Microsoft example is nice, but it is the only animation I ever get to work.

If I remember correctly, you need to write your own BlendingAnimation.

Maybe take a look at CodePlex's XNAnimation, wich is currently being ported to 4.0

http://xnanimation.codeplex.com/

T.

---
Tags: xna, animation, fbx
---


title: Realistic Jumping

text:
# Question
Title: Realistic Jumping
> **Possible Duplicate:**
> How can I implement gravity?

I want to make the jumping that my character does more realistic. This is what I've tried so far but it doesn't seem very realistic when the player jumps. I want it to jump up at a certain speed then slow down as it gets to the top then eventually stopping (for about one frame) and then slowly going back down but going faster and faster as it goes back down. I've been trying to make the speed at which the player jumps up slow down by one each frame then become negative and go down faster... but it doesn't work very well

```
    public bool isPlayerDown = true;
    public bool maxJumpLimit = false;
    public bool gravityReality = false;
    public bool leftWall = false;
    public bool rightWall = false;

    public float x = 76f;
    public float y = 405f;

      if (Keyboard.GetState().IsKeyDown(up) && this.isPlayerDown == true && this.y <= 405f)
        {
            this.isPlayerDown = false;
        }

        if (this.isPlayerDown == false && this.maxJumpLimit == false)
        {
            this.y = this.y - 6;
        }

        if (this.y <= 200)
        {
            this.maxJumpLimit = true;
        }

        if (this.isPlayerDown == true)
        {
            this.y = 405f;
            this.isPlayerDown = true;
            this.maxJumpLimit = false;
        }

        if (this.gravityReality == true)
        {
            this.y = this.y + 2f;
            this.gravityReality = false;
        }

        if (this.maxJumpLimit == true)
        {
            this.y = this.y + 2f;
            this.gravityReality = true;
        }

        if (this.y > 405f)
        {
            this.isPlayerDown = true;
        }

```

# Answer
Define speed and acceleration(gravity). Start with max speed and apply acceleration to it based on time(or frames). There are a few simple equations on the net no big deal. Basic physics apply, it's no rocket science.
> -3 votes

# Answer
I think you're overcomplicating things. The usual way to implement realistic jumping goes something like this:

```
private float verticalSpeed;
private float verticalPosition;

// ...

float groundLevel = highestSurfaceUnderPlayer();

boolean airborne = (verticalSpeed > 0 || verticalPosition > groundLevel);

if ( !airborne && jumpKeyPressed() ) {
    verticalSpeed = initialJumpSpeed;
    airborne = true;  // just jumped off the ground
}
if ( airborne ) {
    float speedChange = -gravity * timestep;  // could add other forces here
    verticalSpeed += speedChange;
    // second order formula minimizes effect of timestep on trajectories:
    verticalPosition += (verticalSpeed - speedChange / 2) * timestep;
    // update airborne state in case we just hit the ground:
    airborne = (verticalSpeed > 0 || verticalPosition > groundLevel);
}
if ( !airborne ) {
    verticalSpeed = 0;
    verticalPosition = groundLevel;  // don't let player fall through ground
}

```

Of course, you also need to update the horizontal position and velocity of the player too, but I've left that out for the sake of simplicity. Also, you'll probably want to implement ceilings too.
> 1 votes

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


# Question
Title: Are there any comprehensive resources for learning Google's PlayN framework?
How do I learn to use the PlayN framework?

The Getting Started page is not enough. I have been searching for some resources to learn PlayN but am unable to find any.

(P.S.: Does PlayN require GWT?)

# Answer
http://proppy-playn101.appspot.com/#1 is a nice tutorial, but far from a complete description. An alternative to PlayN is Libgdx which has become popular.

Libgdx and PlayN have the same cross-platform goals but Libgdx doesn't have Flash support, iOS support is in the works through MonoTouch (same as PlayN).
> 2 votes

---
Tags: android, playn
---


# Question
Title: What makes it hard to protect from hacks/bots in BF3 and Quake Live?
After playing these games, asking other players/admins, and reading online I am led to believe that Quake Live and Battlefield 3 are frequented by bots and there are plenty of hacks of various kinds. I'm confused how this is possible, or even easy seeing how many players have access to these kinds of "tools" (sic).

Isn't it possible for the game authors to digitally sign the game executables so that when they run, the server can ensure only the allowed client is sending commands, thus preventing any kind of abuse? I.e. every player command would be signed by a private key, or symmetrically encrypted (not sure which would make more sense).

I understand that players can look at the running executable's behavior (memory etc.), but if games are apparently so easy to hack, shouldn't most apps be hacked as well (e.g. Skype, all DRM running on Windows etc.)?

# Answer
If it's client-side it's vulnerable.

A hacked client could always be programmed to just send the server the responses it expects, and it doesn't even need to be limited to the client executable. Hacked video card drivers that let players see through walls are also possible, proxys that intercept and modify net traffic, input drivers that work off info in screen grabs, hacked high-visibility player skins, and they're only the crudest examples.

No matter how much technical know-how is needed to construct one of these, as soon as it's done once it can get out in the wild and then every cheater has it.
> 5 votes

# Answer
> Isn't it possible for the game authors to digitally sign the game executables so that when they run, the server can ensure only the allowed client is sending commands, thus preventing any kind of abuse? I.e. every player command would be signed by a private key, or symmetrically encrypted (not sure which would make more sense).

You just copy all that to your cheat client. If the client is required to send it's own hash then a cheat client will just have alternate code that sends whatever is required. There is nothing you can put in the original client that can't be copied to the cheat client.

And since you ask, yes, pretty much all DRM can be hacked, and it happens all the time.

The one thing that can't be hacked, if it's properly made, is license codes for online services. It's pretty trivial to make sure that people at least can't play on the official servers unless they have bought an official license.
> 4 votes

# Answer
Your suggested encryption scheme does not change the premise that games generally run client-side and for a good reason, yet anything client-side is 'in the hands of the enemy'. If the game client needs to know where opponents are, even if they are obscured to the player, then a wallhacker will also have access to this information, as from a technical point of view, both are the same recipient, namely 'the client'. A game developer cannot guarantee to keep this distinction between legitimate software and hacking tools intact and safely communicate with the game client, but not the attacker, because this distinction does not yet exist before the data passes the trust boundary between server and the player's machine and the bad guy gets in control. If this distinction cannot be relied upon, we must assume the game client and the hacker are the same party.

Encryption can be used to communicate safely over an untrusted channel. Superficially, it seems to do exactly what is required here, getting a message from A to B without an attacker being able to read or alter its contents. But there's a catch. The system is useless if the attacker can decrypt the message. The system is equally useless if the intended recipient cannot. In this scenario, the attacker and the recipient are the same person.

Your question concludes in saying: *"if games are apparently so easy to hack, shouldn't most apps be hacked as well (e.g. Skype, all DRM running on Windows etc.)?"*. They should indeed and in fact they are.
> 1 votes

---
Tags: bot
---


title: XNA 2D vehicle wall collisions

text:
# Question
Title: XNA 2D vehicle wall collisions
I am attempting to implement collisions for my truck game, where the truck can drive around the world and hit walls surrounding the level and various randomly placed walls within the level. I am able to get direct collisions working correctly. However, it is getting very complicated and tricky very quickly.

I am trying to accommodate various other collisions such as when a truck is against the wall then turns an adjacent direction or when they reverse into a wall. Both of these result in a slight collision as the image of the truck flips around to the direction the player wants to move. All of this has resulted in a whole lot of if statements to check how I should be fixing the collision. This in turn makes the player jump to random locations and "teleport" around corners, etc.

The rest of my game is fine, I am not completely new to game development or C# for that matter. It's just the logic of collisions. Any ideas on how I can approach this?

Image of the collisions I am trying to resolve:

# Answer
> 1 votes
If your code is turning into spaghetti, it might be that you are trying to build logic to explain something that is unexplainable. I'm guessing about your code (hint, you should post it), but I have a good guess: your collision changes your objects' position/orientation, which changes how it collides, which may trigger more position changes, etc. That will rapidly turn into very strange behavior (like jumping and teleporting, for example).

Solving this will probably take a fair bit of refactoring, but it is for the best. You should try to segregate the logic which determines a collision from the logic that corrects a collision. You should also make sure that there is no strange loop of feedback like I described above; detect a collision, then guarantee that that collision is resolved. A collision correction that results in more collision is not a solution. The process should be

1. Detect a collision
2. Find a solution to fix it, repeat until solution actually works
3. Apply solution and resolve collision. Do not go back to step 1 until something else changes.

A good exercise might be trying to make a flow diagram of the process. If you can't draw it using the basic structures (a straight line, a branch/join, and a single-entry/single-exit loop), then you don't have a good design.

If you can invest the time, I would reccomend this lecture from a pretty great cSci professor on the subject of writing analyzable code. It explains the general answer to the question "why doesn't my code work or make any sense?"

---
Tags: xna, collision-detection, collision-resolution
---