# Question
Title: Is there a portal dedicated to HTML5 games?
*Just to get something straight; by "portal", I mean a website that frequently publishes a certain type of games, has a blog, some articles, maybe some tutorials and so on. All of these things are not required (except the game publishing part, of course), for example, I consider Miniclip to be a flash game portal. The reason for defining this term is because I'm not sure if other people use it in this context.*

I recently (less than a year ago) got into HTML5 game development, nothing serious, just my own small projects that I didn't really show to a lot of people, and that certainly didn't end up somewhere on the web (although, I am planning to make a website for my next game). I am interested in the existence of an online portal where indie devs (or non-indie ones, doesn't really matter that much) can publish their own games, sort of like "by devs for devs", also a place where you can find some simple tutorials on basic HTML5 game development and so on... I doubt something like this exists for several reasons:

1. You can't really commercialize an HTML5 game without a strong server-side and microtransactions
2. The code can be easily copied
3. HTML5 is simply new, and things need time to get their own portals somewhere...

If a thing like this does not exist, I think I might get into making one some day...

# Answer
> 6 votes
Here are some sites you can check out:

# Answer
> 3 votes
http://www.scirra.com/arcade

Although it only accepts HTML5 games made in Construct 2. Also other links you requested:

**Blog:** http://www.scirra.com/blog

**Tutorials:** http://www.scirra.com/tutorials

---
Tags: html5, game-industry, web, online
---


# Question
Title: Is it possible to physically locate a game console?
In theory, is it possible to locate an Internet-connected console? After all, Google Maps can find my computer's location. Can a console connected to the Internet be found in the same or a different way?

# Answer
> 14 votes
As long as you have the IP address, you can get an estimate, just like for the PCs.

# Answer
> 3 votes
The best way to location a game device with WiFi would be using an API like Skyhook Wireless's:

http://www.skyhookwireless.com/

Skyhook have their own database that maps WiFi SSID and MAC Address to a specific GPS (lat-lon) location. This is different and a lot more accurate than IP address location. Skyhook's system can be accurate to 5-50m in urban areas - which is really pretty good. Conversely, IP address geolocation should tell you the metropolitan area the user is in and not much more.

# Answer
> 0 votes
Some versions of PSVita have a GPS.

Game Consoles with WIFI can have some location by IP (same as your mobile)

# Answer
> 0 votes
It can be possible if the console does not require to do connections through a network of the producer. Triangulation will never be accurate, as you can't measure distances. Using times from ping signals is also inaccurate due to unknown load of the network nodes, and the fact that your neighbor may has a higher ping then somebody outside of your country.

Google is using the Geolocation API (in wikipedia) to locate people.

---

The ways consoles can be located:

* If IP is known:
    + average locating through ISP assigned to the IP address Range (e.g by using whois).
    + inaccurate triangulation
* If access to hardware is possible (through software)
    + request locations of present networks (as the Geolocation API does) on the internet
    + ask the user, if you trust them
    + using APIs provided by the manufacturer

---
Tags: console, geolocation
---


# Question
Title: Loading SpriteFont through a different class than Game.cs
I am trying to load up a single SpriteFont to print some debug information. In our current game, we load up both Textures and Music through a ResourceManager. They are both loaded with a filestream, and thus do not require Content.Load

```
SoundEffect soundEffect = SoundEffect.FromStream( fs );

```

Since this ResourceManager does not inherit from Game or is like Game.cs, I cannot use the usual method:

```
SpriteFont spriteFont = Content.Load<SpriteFont>(resource.Key.Item2);

```

Anyone have any idea how I can either: -Load the SpriteFont a different way -Create my own Contentmanager

# Answer
You could do what Gustavo - Gtoknu said and pass the content manager variable into your ResourceManager class OR you could create a new content manager. You'd have to have a reference to your main `game` class, but this is the idea:

```
ContentManager content = new ContentManager(myGameRef.Services, "Content");

```

Where `"Content"` is the root directory to load content from.

Keep in mind that when the `content` variable is disposed, so are all the resources associated with it (ie. anything you loaded), so you want to keep it in scope until you're done with the resources it loaded.
> 1 votes

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


# Question
Title: How do multipass shaders work in OpenGL?
In Direct3D, multipass shaders are simple to use because you can literally define passes within a program. In OpenGL, it seems a bit more complex because it is possible to give a shader program as many vertex, geometry, and fragment shaders as you want.

A popular example of a multipass shader is a toon shader. One pass does the actual cel-shading effect and the other creates the outline. If I have two vertex shaders, "cel.vert" and "outline.vert", and two fragment shaders, "cel.frag" and "outline.frag" (similar to the way you do it in HLSL), how can I combine them to create the full toon shader?

I don't want you saying that a geometry shader can be used for this because I just want to know the theory behind multipass GLSL shaders ;)

# Answer
There is no "theory" behind multipass. There are no "multipass shaders". Multipass is very simple: you draw the object with one program. Then you draw the object with a *different* program.

You can use D3DX stuff like FX files to hide these extra passes. But they still work that way. OpenGL simply doesn't have a hiding place for it.
> 16 votes

# Answer
Render the object with the cell shader, and then re-render it with the outline shader.
> 1 votes

# Answer
There are some people who know a great deal about GLSL, so I hope they come set the record straight, but based on what I've seen, you should be able to, in your fragment shader, do something like this (pseudocode, I'll leave the actual GLSL up to the people who know it better):

```
out vec4 fragment_color
vec4 final_color
final_color = flat_color
If this fragment is in shadow
    final_color = shadow_color
If this fragment is an edge
    final_color = edge_color
If this fragment is a highlight
    final_color = highlight_color
fragment_color = final_color

```

By using `if`s in this way, you get something like multiple passes. Does that make sense?

*Edit:* Also, hopefully this question on SO helps dispel some misunderstanding.
> 0 votes

# Answer
In OpenGL 4.0 there are uniform subroutines. These allow you to define functions that can be swapped out at runtime with very little overhead. So you can make 1 function for each pass. Also 1 function for each shader type.

There's a tutorial here.

For older OpenGL versions your best bet is to either have a bunch of different shaders and swap between them. Otherwise you can add together values that you multiply by a uniform that is either 0.0 or 1.0 to turn it on or off. Otherwise conditional if statements can be used but OpenGL will execute all possible outcomes every execution/pass so make sure they aren't too heavy.
> 0 votes

---
Tags: opengl, shaders, glsl
---


title: Dynamic body implementation

text:
# Question
Title: Dynamic body implementation
I am writing a 2D game where one of the characters has some very particular requirements. This character is a body with no particular shape (similar to a fluid, but not so much), it has to be able to grow and shrink (as in actually growing, not just scaling), and it has to have collision detection (even if it's basic). Because of this requirements, it obviously can't be based on a sprite, so direct rendering of the shape should be the logical thing to do.

I assume this is no easy task, but I just couldn't find a good physics engine that covers these requirements (or at least no tutorial on how to do it; I particularly searched for Box2D tutorials).

Is there a way of doing this with Box2D, SDL, or any other physics or game engine out there?

If not, what's a good place to start? I am really clueless as far as soft-body physics are concerned.

# Answer
> 1 votes
I'd go with spheres.

When you grow, add new spheres to the existing ones (at different directions) more to the 'base spheres', less to the farther away ones, organized like this :

Sphere B is 100 units from sphere A at "vector" 0.7 ; 0.3 ; -0.4

or just use the final vector 70.0 ; 30.0 ; -40 to connect B to A.

You can even predefine the link points on the spheres so you always grows the blob the same way or go more random if you'd like that.

If the blob must "animate" you can simply interfere with the distance the spheres are connected with :

Say a "heart beat" value

```
float v=1.0 + sin(time)*0.2;

```

that affects the vectors connecting the spheres.

Using predefined tweak values for each distance can be used to break uniformity:

```
//each connection has this values:

Vector v; // the (70.0 ; 30.0 ; -40) values
float timediff; //animates a bit before or after if <0 or >0
float influence; //at zero, there is no animation, at 2.0 the animation is twice the base one

Vector vOut= v *  (1.0 + (sin(time+timediff)*0.2*influence));//time is the global time, 0.2 is the global animation power

```

Drawing can be done using simple sprites or using a particle engine (so for example, SDL can be used).

# Answer
> 0 votes
I'm not entirely sure about what physics engine or language you are using, as Box2D and SDL are used for two different languages...

Either way, I'd recommend using circles and using those to generate a jelly-like form, and just giving them a high friction, so that the circles don't fly everywhere.

I'm not sure what you mean by "actually growing, not just scaling", because growth of a character is scaling of the sprite, and raising different stats...

please, take a look at the Wikipedia article for "soft body dynamics" and http://cg.skeelogy.com/?download=SoftBodyPhysicsTutorial these have been recommended for soft body objects (which is really what your character is, it just has a container around it).

---
Tags: physics, body, rigid-body-dynamics
---


# Question
Title: What's the best way to write fade in out function?
I want to create a continuous fade in and out.

I'd like to have some function `F(time)` that returns values increasing from 0 to 255, then from 255 back down to -255, and repeats, as time progresses.

# Answer
I know the question has been answered but just for old times sake here is the optimized classic way (works only with fixed steps but takes only 2 bytes ;-) )

```
//init:
unsigned char value=0;
unsigned char d=1;

//in loop:
value+=d;
if((value==0) || (value==255))
 d=-d;

```
> 1 votes

# Answer
What you're looking for is a periodic function like Sine. Here's how you can use Sine to achieve what you're looking for:

```
Create a loop counter
Begin your fade loop
    Increment your loop counter
    fade_amount = 255 * sin(loop_counter)

```

It's as simple as that. Since `sin(loop_counter)` will cycle from -1.0 through 0 to 1.0 and back again, you just multiply it by the maximum value you want.
> 10 votes

# Answer
You can also use a tweening library to smoothly fade in and out such as cpptweener.

http://code.google.com/p/cpptweener/
> 1 votes

---
Tags: animation
---


# Question
Title: Best approach to get clicked objects from a display list (2D)
I'm implementing a display list to manage my visuals on screen.

I want to know which object is clicked.

My objects already have z-order variable.

With my current knowledge (almost nothing) the only thing which comes to my mind is make a linear search and get all the objects which contains the clicked point. And then select the object with the highest z-order. But I know there are far better approaches.

I think it's something with trees (binary search?). \- container display objects and search recursively?

just don't know where to start looking, for this concrete case. Any hint link or concrete solution is welcome.

# Answer
You're on the right track. The thing you're looking for is a **space partitioning** data structure. For a 2D system I'd go ether with a **quadtree** (if object sizes vary a lot) or a simple **grid** (if object sizes are similar). I've already written two answers on the subject, so instead of repeating myself I'll just link you to them:

On the other hand you should consider if this is really needed based on the amount of objects you expect to be added to the display list. I pondered the same in my own project and in the end deemed it unnecessary and used the linear approach instead. It's been more than enough for me.
> 4 votes

---
Tags: 2d, algorithm, search
---


title: How would I use JBox2d in Java?

text:
# Question
Title: How would I use JBox2d in Java?
So I did some research and a found Box2d. I then proceeded to download it and the testbed. Now that i have it, I don't know how to properly use it. I'm looking for a clear simple answer on how to use the engine.

The things I did was that I put it into a lib folder and referenced the JBox2D jar file. After that i got stuck. How can i use this to program games for android?

I'm very confused since Box2d was intended for C++.

# Answer
I've just started using libgdx (http://code.google.com/p/libgdx/) for Android development. They have a JNI wrapper for Box2D (java wrapper for the native code). They also have plenty of example code which you can look at to see how they use Box2D.

If you view the video at their Google code page, it will explain how to easily setup a project. Then you may want to go to the wiki, or I found that the guy at http://steigert.blogspot.com.au/ is working his way through an extremely comprehensive but easy to understand tutorial.

If you are interested in looking straight at some Box2D code which runs on Android, here are plenty of tests here:

http://code.google.com/p/libgdx/source/browse/#svn%2Ftrunk%2Ftests%2Fgdx-tests%2Fsrc%2Fcom%2Fbadlogic%2Fgdx%2Ftests%2Fbox2d

There is also source code for complete games, some which use Box2D:

http://code.google.com/p/libgdx/source/browse/#svn%2Ftrunk%2Fdemos

You'll find development quite fast, because you can run your games on a PC as well as on the phone, so most of your debugging will be done on the PC. The process for setting up both the PC and the Android code is described nicely in the video I described above (the guy narrating is quite funny).
> 2 votes

---
Tags: java, android, box2d
---


# Question
Title: Choice of open source license for some components, closed source for others
G'day,

I am working on a set of multiplayer games, where different games play against each other (e.g. you play a Tetris clone, I play an Asteroids clone, but we are both competing against each other). All the games would be based on the same underlying framework written specifically for this project.

I am struggling to comprehend how I would license this so that:

* The underlying framework is open source, so other people can create new games based on it.
* Some games built on the framework are open source
* Other games are closed source

The goal is to have two bundles on something like the Android market:

* One free and open source package which has a collection of games
* Another "premium" (although I dislike that word) paid package which has a different collection of games.

Usually I am fond of permissive licenses such as MIT/BSD, however I would prefer something more in the vein of the GPL for this. This is because for software such as the snes-9x SNES emulator, which is a great piece of software, there is a ton of poor quality versions being sold, whereas it would be preferable if there was just one authoritative version which was always kept up to date, and distributed for free.

If the underlying framework was GPL'd, would I be able to build closed source games on top of it?

Thanks for your input.

**Edit:** @JasonMorales gave me a little more to think about. There are a couple of ways it could be put together:

1. Main application, handles networking, main menu's, etc, and loads games as plugins.
2. Games are all separate applications, and the framework will provide a menu, networking, etc.

The first is good because there is guaranteed to be consistency between games. It is not good, however, in the sense that I can't imagine how it would be deployed via the Android market. That is, you go to the market, and download a new game. If it was more akin to a regular package manager, this game would depend on the main application and it would install quietly. I'm not convinced the Android market works like this though.

The second would deploy easier, because each time the user downloads a new game, it does exactly what they expect: downloads a game and gives them a nice icon for them to open it from. There are obviously several downsides to this too though, such as if the framework decides to update its menu or network implementation, the other games will not get this update unless they re-release themselves.

But because I'm ranting, I may create a new question for these matters.

# Answer
> 0 votes
It depends on how your framework links with the game code. The framework doesn't have to be open source to allow other people to make games for it, you could release it either as a program that people can write plugins for, or a closed source library that people link against. In that case, you maintain full control of the framework.

It sounds like you want the framework to be open source though, in which case there are two options. If your framework is a library that other programs link to, you can release it as LGPL and people can then develop closed or open source programs that use it. If you develop your framework as something that the game modules act as plugins, it seems that they would be required to be full GPL as well: http://www.gnu.org/licenses/gpl-faq.html#GPLAndPlugins

# Answer
> 6 votes
This is a common misconception, but *the licence is not a property of the code.* It is a document that tells people one way that they can legally use your code. There can be as many or as few different licences available as you like, and you can decide how to allocate them to people. You can give one person a GPL licence and everybody else a closed licence if you like. The only catch is that the GPL licence then allows that person to also give the GPL licence to others, which is fine because that's how it's supposed to work, but it does not stop you having the right to allow people to make closed source applications based on that code too.

Basically, if you own the copyright to the code, you are fully at liberty to offer a GPL licence on the code *AND* to let people make closed-source applications with it also. Offering a GPL licence only affects the code of people who have chosen to accept that licence in order to facilitate their own usage. It does not give them rights over the code used by those who make closed source derivatives with your permission. Closed-source licensees have a licence from you to make a closed-source game with your code and the GPL does not enter the equation.

The LGPL was invented as a middle ground for this situation, as it basically means that the GPL only applies to the library code, whereas the code linked to it stays under that creator's licence. This might work in your situation as it keeps the framework open while protecting the licensee's new work. But the definition of 'linking' may not easily apply to your framework and you might end up having to amend the licence, making it less worthwhile.

# Answer
> 0 votes
> If the underlying framework was GPL'd, would I be able to build closed source games on top of it?

If you hold the copyright to the code then of course you can use it for closed source, so long as it doesn't depend on other GPL (or similar licence) code.

---
Tags: open-source, licensing
---


# Question
Title: Which code module should map physical keys to abstract keys?
How do you bridge the gap between the library's low-level event system and your engine's high-level event system? (I'm not necessarily talking about key events, but also about quit events.)

At the top level of my event system, I send out `KeyPressedEvents`, `KeyRelesedEvents` and others of this kind. These high-level events only contain the abstract values of the keys (they don't say that Space way pressed, but that the JumpKey was pressed, for example).

Whose responsibility should it be to map the "JumpKey" to an actual key on the keyboard?

# Answer
> 1 votes
You probably have a message pump somewhere in your gameloop where you receive the keypress messages from your system. That's usually where you'd use a class like 'keymapper' or something, which holds a map of keys and actions/events. So, you'd look at all keys changed, lookup their mapped action/event and fire that. For example, releasing 'w' might resolve to 'w is no longer pressed' which in turn might be looked up to be something like '-forward' or 'playerForwardMovementDecreaseEvent'.

# Answer
> 2 votes
If you'd like another perspective on this, check out this blog post about "Wiring physical devices to abstract inputs". It covers a lightweight mapping framework in close detail and demonstrates a fundamentally different approach to the problem.

It basically works as follows: Input from all devices is gathered in a structure that can be queried from all systems that want to subscribe to input. A system can then define "Actions" (single keystrokes or chords) for which the abstract device structure is queried. If the specified action has been performed on the device, the `()`-operator of the action returns `true`, indicating that the "input condition" the system has been waiting for is fulfilled.

**Note**: This system relies on C++ templates to avoid run time type identification. If you are not coding in C++ you can probably just use a regular dispatch mechanism provided by your language as performance will probably not be your primary concern then.

---
Tags: events, keyboard
---


title: Animation Blending Basics

text:
# Question
Title: Animation Blending Basics
Say I have a framework with characters that can run and walk and of course, stand still.

Am I right in thinking that animation blending is the process of smoothly transitioning between these by generating dynamic animations at runtime?

If so, what is the basic theory of how this works, and how would I implement it?

# Answer
Character animation blending is more general and can be used for:

* Computing smooth transitions between 2 clips;
* Creating completely new animations from existing ones (potentially more than 2 at the same time);
* Achieving IK-like behaviors;
* etc.

The basic idea is that for two identical skeletons with different animation clips, for each joint rotation, you compute in-between values. Animation clips are represented with rotations. So linear interpolation is not what you should use if you want accurate results (even if you are using Euler angles). You can use slerp for example but more complex solutions exist.

This is a complex problem with complex solutions. Basically, if you have two animations clips A and B:

* If A and B are completely different (blending jump and swimming), then chances are you will have strange/funny results;
* If A and B are similar (two walking animation clips), then, you must first synchronize them to blend them when both left feet are on the ground for example.
* etc.

If you are interested, I suggest you start by reading this article so that you can better understand what the difficulties are: http://graphics.cs.wisc.edu/Papers/2003/KG03/regCurves.pdf

It is not the most up to date one, but it is easy to read.

I hope this helps. Best regards.
> 21 votes

# Answer
First off, I assume you are talking about skeletal animation (especially 3D graphics) since animation blending pretty much only applies to skeletal animation. If you are talking about 2D sprite-based animations (you didn't specify in your question) then you can pretty much forget about animation blending.

With that out of the way...

> Am I right in thinking that animation blending is the process of smoothly transitioning between these by generating dynamic animations at runtime?

That is pretty much what the term means, yes. That phrase "generating dynamic animations" is a tiny bit misleading however; that brings to mind procedural animation and that isn't exactly what you're doing.

"Animation blending" is when you transition between two animation clips by using a bit of both animations with the weighting of one clip going up while the weighting of the other clip goes down. This works best with skeletal animation, so that the rotation of each joint is set to a midpoint between that joint's animation in two different animation clips, with the weighting of each clip changing over time. That is, you'd calculate the rotation of each joint something like:

`rotCombined = weightA*rotA + weightB*rotB`

Now, while animation blending works best with skeletal animation, you can also do it with vertex animation (eg. MD2). This is more of a historical note because few modern game engines use vertex animation, but you can set the vertex positions in the same way, as a weighting between the vertex position in two different animations. This could result in some weird looking interpolations (eg. parts of the mesh collapsing or turning inside-out) if the two animations were too different, whereas skeletal animation ensures that the various parts of the mesh stay whole.
> 5 votes

---
Tags: c++, animation
---


# Question
Title: Why wont the LibGDX's main class Initialize on Android Launcher?
So I was searching for different ways that could suit me in programming and came across LibGDX. Naturally I looked at the tutorial. As I was doing it, I was following the steps word for word, except naming the classes. In the end, I was able to create the desktop launcher for the game but not the android launcher.

The following error is my error: Cannot instantiate the type Game (Game is the name of the class)

I got the tutorial from http://steigert.blogspot.com.au/2012/02/1-libgdx-tutorial-introduction.html The link in the tutorial is the original but it uses jogl instead of lwjgl.

# Answer
> 1 votes
From the wiki: http://code.google.com/p/libgdx/wiki/ProjectSetup

> Note: The folder really must be called "libs", a naming convention forced on us by the Android Eclipse plugin.

Without this, your code will still compile within Eclipse, because it is compiling against gdx.jar from the (referenced), desktop project, but won't run on an Android device because gdx.jar wasn't in the libs dir. Although I too have come across (and enjoyed) the tutorials you pointed to, it seems like this point was missed.

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


# Question
Title: Any good smartphone simulators available?
I'm trying to find a good smartphone simulator to test HTML5 games on. Doesn't matter if it is only 1 phone or a library of phones, iOS or android. As long as it's as close as it can get to the touchscreen experience.

Any suggestions?

# Answer
> 5 votes
Install the Tegra Android Development Pack. It includes Android simulator, the SDK and preinstalled Eclipse just in case: http://developer.nvidia.com/tegra-android-development-pack

Then go to the android-sdk-windows folder and open AVD Manager.exe. In that screen you can create a new emulated device with any specs you want. Then use Start to open it. It will have internet connection so you can try your remote app.

The thing is that none of the emulators (iOS/Android) are near the performance most devices would give you, so you can't measure performance and framerate.

---
Tags: android, iphone, html5
---


# Question
Title: How do I create a big multiplayer world in UDK?
I want to create a big multiplayer world in UDK and I'm having a few difficulties.

1. I created the biggest terrain possible but then any terrain related action I do takes forever. However, I've seen videos of people make same size terrain and working without a problem. My pc is strong enough, so maybe someone can tell me what I'm doing wrong.
2. I want to make it even bigger then the biggest terrain size, so I was thinking of doing level streaming but then I read that streaming is working server side which means if I have a player on every terrain all terrains will still be loaded and I want to save as much memory possible so it will work well online.

Thanks for any help you can give.

# Answer
1) You need to think about a streaming solution, stream in and out parts of your level as you require them (radial streaming, streaming volumes, etc...)

2) I think you need to rethink your plan. Unreal isn't made to support the MMO type of games (it's one of your tags).
> 3 votes

# Answer
cryengine3 is an automatic open world sandbox editor and can make the world open for you. I know where you are coming from and what kinda gameplay you have in mind coz i also have the same desire to make open world games. If you wanna use cryengine3 pls do so to make it possible for you to achieve your dream but even though there are good sides to cryengine, there are also the bad sides. The bad sides are that until now the crydev ( cryengine ) is still a baby in providing you or anyone else with tutorials and info about the depth of the engine, but i am sure as years pass by the community will develop and grow so that anyone can reach out for help and gain knowledge by just searching and practicing them out, but for now it is a difficult task to do so. I myself used the cryengine as soon as it came out, but came towards many blocks and i couldnt search for any help for all those small needs, But then i quickly changed my engine and chose to use the unreal engine 3. Why?, well first of all the unreal engine ( UDK ) has a vast amount of resource for the community and people of interest like you and me and even though it there is no info out there which teaches us how to make an mmo open world game ( which is strange ), i also agree with you that there are developers out there who has made great MMO RPG games using UDK, so guess its a secret. I believe that one day, some one will put a tutorial about making a open world Game with UDK and this will solve everyones problem and even if no one puts it out there for us to read, i am sure that one day UDK will update and suddenly it will have kismats or something else which will allow us to easily create a MMO type game just like what cryengine is doing right now. So my suggestion and recommendation is to study the UDK and just hold on until some kind of resource about making MMO games will be found by you in the search engine or it will be given to you in a free update.
> -3 votes

---
Tags: mmo, multiplayer, terrain-rendering, udk, terrain
---


# Question
Title: How can I create a rectangular SDL surface filled with a particular color?
I'm learning SDL. I'd like to create rectangular surface filled with a flat color (not an image). Below is my code -- it compiles fine, but doesn't work.

I'm passing the function these parameters:

```
SDL_Surface*  m_screen = SDL_SetVideoMode(
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
  SCREEN_BPP,
  SDL_SWSURFACE
);
SDL_FillRect(
  m_screen,
  &m_screen->clip_rect,
  SDL_MapRGB(m_screen->format,0xFF, 0xFF, 0xFF)
);
...
Button button(m_screen,0,0,50,50,255,0,0)
...
...
Button::Button(SDL_Surface* screen,int x,int y,int w,int h,int R, int G, int B) {
      SDL_Rect box;
      SDL_Surface * ButtonSurface;
      ButtonSurface = NULL ;
      Uint32 rmask, gmask, bmask, amask;
      #if SDL_BYTEORDER == SDL_BIG_ENDIAN
         rmask = 0xff000000;
         gmask = 0x00ff0000;
         bmask = 0x0000ff00;
         amask = 0x000000ff;
      #else
         rmask = 0x000000ff;
         gmask = 0x0000ff00;
         bmask = 0x00ff0000;
         amask = 0xff000000;
      #endif

      box.x = x;
      box.y = y;
      box.w = w;
      box.h = h;

      ButtonSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, box.w,box.h, 32,
                                    rmask, gmask, bmask, amask);

      if(ButtonSurface == NULL) {
         LOG_MSG("Button::Button Button failed");
      }

      SDL_FillRect(screen,&box,SDL_MapRGB ( ButtonSurface->format, R, G, B ));

      //ut.ApplySurface(0,0,ButtonSurface,screen);
      SDL_BlitSurface(ButtonSurface,NULL,screen,&box);
   }

```

What am I doing wrong here?

# Answer
In SDL, whenever you're not seeing things drawing, or in drawing in completely the wrong color, eg. white, your first thought should be, "What is wrong with my colour formats?". You'll want to check your bpp depth as well. I think due to changes from prior versions of SDL (could be wrong here) some sources say this is *bits* per pixel, others think it's *bytes* per pixel. In SDL 1.2.14, it's supposed to be bytes per pixel IIRC.

Are you calling this in a loop? Nothing will happen if you're not calling it in a loop -- of course -- your app will just quit immediately. Sorry, had to ask.

Best advice I can give you is go and follow LazyFoo's SDL Tutorials... each time I had something wrong in regards to the basics, that's where I headed (after looking at a bunch of other references), and it always solved the problem. Write minimal test cases based on his examples and you should be A for away.
> 6 votes

# Answer
I don't see an SDL\_Flip

SDL is double buffered so you need to fill the buffer, then display it.

It also looks like you are mixing up your object and rendering your object (not necessarily a bad thing, but it will start to get confusing when you have multiple objects)

As Nick stated, get yourself over to LazyFoo, those tutorials are great, up to date, cross platform, and he lets his schooling as a software engineer bleed through in some of them, so you get a taste of some advanced concepts like threading. I have not found a good substitute.
> 2 votes

---
Tags: c++, sdl
---


# Question
Title: How can I resize a set of sprite images?
Hey StackExchange GameDev community, I'm attempting to resize series of sprites upon instantiation of the class they're located in.

I've attempted to use the following code to resize the images, however my attempts have been unsuccessful. I have been unable to write an implementation that is even compilable, so no error codes yet.

```
    wLeft.getScaledInstance(wLeft.getWidth()*2, wLeft.getHeight()*2, Image.SCALE_FAST);

```

I've heard that `Graphics2D` is the best option.

Any suggestions? I think I'm probably best off loading the images into a Java project, resizing the images then outputting them to a new directory so as not to have to resize each sprite upon class instantiation. What do you think?

Photoshopping each individual sprite is out of the question, unless I used a macro.

Code:

```
package game;

//Import
import java.awt.Image;
import javax.swing.ImageIcon;

public class Mario extends Human {
    Image wLeft = new ImageIcon("sprites\\mario\\wLeft.PNG").getImage();

 //Constructor
    public Mario(){
        super("Mario", 50);
        wLeft = wLeft.getScaledInstance(wLeft.getWidth()*2, wLeft.getHeight()*2, Image.SCALE_FAST);
    }

```

# Answer
> I've attempted to use the following code to resize the images, however my attempts have been unsuccessful. I have been unable to write an implementation that is even compilable, so no error codes yet.

That code looks okay to me -- but I don't know Java very well. You may want to post another more-specific question should you elect to go the route of resizing at runtime if you still can't get it working, however:

> I think I'm probably best off loading the images into a Java project, resizing the images then outputting them to a new directory so as not to have to resize each sprite upon class instantiation. What do you think?

That's correct -- it'd be much better to resize the images at build time or author time instead of at runtime, because then *you* are paying the cost for that operation once, instead of your *users* paying that cost every time your game loads. It may be a trivial cost, but its simplifying.

You could write your own code to do this, and it might be an excellent learning experience for you. But you could also find a tool to do it for you. Photoshop with a macro might be viable, for example, or you could use Gimp with this batch processor plugin (see here for a guide on batch resizing a lot of images). If you poke around on your favorite search engine for things like "batch image resizer" you'll come up with a few results as well, such as this one.
> 2 votes

---
Tags: java, image
---


# Question
Title: What do I need to program games for the PS3?
> **Possible Duplicate:**
> What do I need to develop for the Playstation 3?

How can an amateur programmer have access to learn programming on PS3, and test the developments on own PS3? Not only use of CPU but also of GPU.

# Answer
> 8 votes
You need a development kit from Sony to do this legitimately. These are not cheap and are intended for big AAA games companies.

This is the case regardless of whether you intend to sell what you make.

---

If you just want to get a game on a console, probably the best bet is the Xbox 360, with their Live Indie Games program.

See also: The true cost to get my XNA game on XBox?

# Answer
> 5 votes
If you are interested in programming the PS3's Cell processor with its SPUs, you can download the Cell SDK and the simulator for linux here

If you have access to a blade-machine you can directly compile it for the CELL and execute it natively. It used to work with old PS3 OS versions too, unfortunetely they removed the ability to install linux.

However, its fun and a great learning experience in case you like low level programming :)

---
Tags: playstation3
---


# Question
Title: When should I decide what language and platforms I will use for a project?
During your development process, when is the recommended phase to decide what platform to aim for, and what language to use?

I figured that it would be better to choose at the beginning what would be your target platform, as it would affect your design decisions, and limit the language you are supposed to use.

However, I have heard several stories of people developing their game with whatever language they were the most confident with, and then porting it to the various platforms.

So, what is the best moment to choose? Before, during, after? If there is not **one** best choice, what factors should affect the decision?

# Answer
> 9 votes
You have to make this decision up front, before you start on any sort of development. Until you decide what language(s) and platform(s) to utilize, you can't actually do anything but concepting, design and preproduction.

That said, you may want to allow for future ports or expansion to factor *in* to your decision. If you want to port to multiple desktop platforms (Mac, Windows for example) it may be better to opt to use OpenGL as your rendering back-end (or some other cross-platform abstraction/rendering engine). Otherwise you will generate more work for yourself in the long run. Likewise with language choices -- Objective-C is weakly-supported just about everywhere but on the Mac, so if you're developing for the Mac, you may want to try and minimize your actual use of Objective-C to just the required bootstrapping bits.

However, do consider that there's generally no amount of up-front agonizing over technological choices that will make porting trivial, so your better off simply making a decision and moving on to creating a real product instead of faffing about over hypothetical porting issues that won't exist until you actually have a thing to port.

Also keep in mind that unless you have the target hardware, porting to it will be difficult. If you don't have or never plan to buy a Mac, don't bother including considerations for Mac porting into your plans right now. Similarly, restricting your language choices to things you know really well (unless you're making a smaller project for the purposes of education) is usually a good idea.

# Answer
> 2 votes
I just write the whole thing in perfect pseudo code, then port that.

But seriously, ***before you start***. I don't think porting to another platform **after** the project is done should ever be part of the original plan.

Beginners should develop in what they're most comfortable with. Those stories you heard of people porting after their project was complete likely didn't plan on that from the beginning.

# Answer
> 2 votes
your feature set, and requirements should be a determination on any decision you make toward your game design.

the decision of platform that can either be determined on want (I want to make this kind of game for X system), analysis (this platform has the ability to support some really cool features that I want in my game), or cost (in order to develop for this platform I would need to use this SDK which costs Y dollars)

SDK/development environment some systems can only be developed for with specific SDKs, and others there are SDKs specifically designed to port to multiple targets.

For the most part the differences between languages can be viewed as marginal (I know that this can be cause for debate, but some differences are really marginal), but it is mostly based on the SDK being used, and what languages it supports. to develop for Unreal your options are unreal script, or c++ (kinda). for XBox360 your options really are just C#. yes you could probably find a way to do any platform with c++, but sometimes that does throw away possible benefits the platform can offer.

# Answer
> 2 votes
Changing languages is hard, adding support for a new platform is easier, but planning everything out in advance is by far the easiest.

Of course, it is practically impossible for everything to go to plan, and so you should design systems uncoupled from their underlying implementation.

> So, what is the best moment to choose? Before, during, after? If there is not one best choice, what factors should affect the decision?

If you are unsure then you haven't done enough research. Figure out everything you need before you begin. It may take days to do, but it's better than spending weeks having to port/rewrite. Eventually you will have to make a decision, but with plenty of research you will have narrowed your choices into a selection that can't go wrong.

---
Tags: cross-platform, platform
---


# Question
Title: How do I get the source code from a Google Code game project?
I'm trying to get the Hedgewars source code. When I went to the downloads tab, it doesn't specify which is the actual game. I tried downloading it using the SVN Checkout on Tortoise, but it seems like it doesn't work on the browse section of Source.

(Hg\>project\_files\>Android\_build\>SDL-android-project)

I then proceeded to the wiki but I got stuck at step two because I don't know anything about Mercurial. Some other things I don't know from the wiki is "FreePascal" "Android NDK" and "Tar" files. They are new to me so I am really confused.

So my question is, how can I download the source code from Hedge Wars for Android without having to browse the source code inside the source tab?

# Answer
Google Code supports several version control systems (SVN, Mercurial and git as of this writing). Hedgewars appears to be using Mercurial, as you can see from the Source -\> Checkout tab on Google Code. To get the code, you must clone the repository as described on that page, using either the command line Mercurial tools or a GUI wrapper like TortoiseHg.

In general, to get the code from any Google Code project, you navigate to that project's Source -\> Checkout page and follow the instructions. Some projects will also create .zip or tarballs of the their code and host them on the Downloads tab, but Hedgewars does not appear to do this currently, so you'll have to get the code the aforementioned way.

Some projects also provide a wiki page, like the one you linked, that further explain any dependencies or special steps you'd need to take to acquire and build the code. Not all projects do this, however.
> 5 votes

# Answer
To checkout the source code you need to use mercurial as there is no official svn repository. Simply `hg clone https://code.google.com/p/hedgewars/` as stated on the google code page.

If you are not comfortable with the command line you can try using one of the Mercurial user interfaces.

---

If you don't want to use mercurial the download section on the hedgewars website has a direct link to a compressed archive of the source code.
> 2 votes

---
Tags: android
---


# Question
Title: Representing heightmaps, on disk and when drawing
This is a conglomeration question when answering please specify which part you are addressing. I am looking at creating a maze type game that utilizes elevation. I have a few features I would like to have, but am unsure as to some of the implementation.

I have done work doing fileIO maze generation (using a key to read the file, and then generate the level based on that file), but I am unsure how to think about this with elevation in the mix. I think height maps might be a good approach, but don't know how to represent them effectively. for a height map which is more beneficial XML(containing h\[u,v\] data and key definition), CSV (item1 is key reference, item2 is elevation), or another approach that I have not thought of yet?

When it comes to placing the elevation values themselves what kind of `delta`h values are appropriate to have it noticeable at about a 60`degree` angle while not really effecting gravity driven physics (assuming some effect while moving up/down hill)?

I am thinking of maybe going to procedural generation at some point, but am wondering if it is practical to have a procedurally generated grid (wall squares possibly same dimensions as the open space squares), or if designing to a thin wall open spaces is better? this decision will effect the amount of work need on the graphics end for uniform vs. irregular walls.

EDIT: Game will be a elevation maze shooter. Levels/maps will be mazes with elevation the player has to negotiate. Elevations will have effects on "combat" vision, and movement.

# Answer
> I am thinking of maybe going to procedural generation at some point, but am wondering if it is practical to have a procedurally generated grid (wall squares possibly same dimensions as the open space squares), or if designing to a thin wall open spaces is better?

Depending on how you go about things, I'd say it doesn't matter - either is good. Nethack and many roguelikes are a great example of how "fat walls" look when generating mazes/dungeons at a single height. I think it might possibly make your job easier, since all you need to store the level data is one array (as opposed to essentially two different arrays with thin walls: One for "inside-grid-cells" and one for "between-grid-cells") although Nethack is only one height.

I think you should start with whichever one is less work (probably fat walls), because honestly to a gamer what matters more is that the games logic is consistent and well-implemented rather than realistic; so it doesn't matter that fat-walls seem weird so long as they work and are bug-free.

> I think height maps might be a good approach

They aren't. If your maze is a bunch of rectangular (or polygonal) prismatic rooms connected by hallways, a heightmap is quite unsuitable. This is because you give up some huge things: Rooms cannot ever be above each other for instance, because for every z-level there is only one value. The heightmap, in other words, is a function, which can have only one output for a given input, this is quite an illogical constraint (why should it be the case?).

I say this especially because if you accept that assumption, your question becomes trivial. Just generate a 2D flat map as usual, generate (randomly?) a height for each room, flood fill, paint gradients in connecting hallways, done. Then, yes, perhaps a "heightmap" is appropriate as you say.

An alternative way of representing is to simply keep a list of tiles which have walls. The coordinates are 3D, because you'd need a 3D grid for storing a 3D level.
> 1 votes

---
Tags: procedural-generation, level-design, heightmap
---


# Question
Title: How to integrate game logic in game engines
Recently I'm working on a 2d game engine example in .Net with C#. My main problem is that I can't figure out how I should include the game logic within the game. Currently I have a base engine which is a set of classes that they are running sub-systems like `Render`, `Sound`, `Input` and `Core` functionality. There is an editor which helps the user to add resources, build levels, write scripts and other stuffs.

I came up with an idea to use Reflection and `CSharpCodeProvider` from my editor to compile the written code. This way I can get an executable of my product too. This way is quite well but I would like to know what's really the solution and architecture to do this.

My engine's role is 2d platform. The scripting language is C# right now because I can't consist any other embeddable language for now. The game needs compilation and `CSharpCodeProvider` is the only way for me to do it meantime.

# Answer
> I came up with an idea to use Reflection and CSharpCodeProvider from my editor for compile the written codes, in this way I can get an executable of my product too. This way is quite well but I would like to know that, what's really the solution and architecture to do this.

This is a huge security risk, the user can use reflection or edit the code dom to rewrite any and all of your application. Additionally to being an easy attack vector for viruses, keyloggers, and the rest it would be impossible to enforce any anti cheating measures because of this.

Look into scripting. Iron Python and CSScript are widely used and have a good reputation. The more commonly used scripting language is Lua but Lua is a pian to integrate with a .net application. At least last time I tried.
> 1 votes

# Answer
I solved a very similar problem a while back. I was in Javaland, but the same principles apply.

What we did was provide a scripting API via the methods of an API class. Then, user code was wrapped inside a child of the API class, that class instantiated, and the user-defined `run()` method called.

To mitigate security concerns, we used Java role-based security, with draconian settings. (Instances of the child class had access to their own methods only). This essentially means that you're restricting the users to the API you define, while remaining in a single language environment.

I believe that you can do the same in .NET by using Role-Based Security

PS: This is the same method that Processing uses.
> 1 votes

# Answer
I assume from your question that the entire game is C# (the engine is C# *and* the scripting language is C#?). Are you are using a 3rd party engine or rolling your own?

Can you separate your game into logical modules? For example, a core engine module for all the general bits (rendering, audio, UI primitives, etc.) and a game module with all the specific bits (game logic, defining the UI, what your buttons do, which textures to load, your level format) ?

At a higher level, consider whether you are really in a situation where you need a script engine, or would clever code separation + data meet your needs until & if you decide you need to go down that path? Yes, scripts can give you the ability to alter game behavior on the fly/without recompiling, but it does add an extra layer of complexity. If you are experimenting with tech that's one thing, but you may find that you just don't need it.
> 0 votes

---
Tags: c#, .net
---


title: Where to store shaders

text:
# Question
Title: Where to store shaders
I have an OpenGL renderer which has a Scene member variable. The Scene object can contain N SceneObjects. I use these SceneObjects for storing the vertex position and any transforms. My question is, where should shaders be stored in this arrangement? I guess they need to be in a central location because multiple objects can use the same shader. But then each object needs access to the shader because it needs to set attributes into the shader. Does anyone have any advice?

# Answer
> 9 votes
You should have a shader pool where all shaders are stored. Once the pool is filled, objects are bound with these shaders (think "bound" as object-references-shader.) Many `SceneObjects` could share the same shader object (be it OOP or whatever) and only access it by referencing the shader in the pool.

Then, for each `SceneObject`, you just set the attribs/uniforms, bind the shader in OpenGL and draw. You should consider batch-rendering the objects which share the same shader to avoid changing OpenGL state (or at least accounting for it.)

Whenever you load a new object, just bind it with the shader already found in the pool. If you're not preloading shaders and it's the first time you're using the shader, add it into the pool. You should also delete shaders from the pool if you're not going to use them anymore (i.e. counting references.)

---
Tags: architecture, shaders, opengl-es
---


# Question
Title: How do I make a collision between AABBs slide?
I have a room with objects inside. Each object has it's own AABB.

I know how to check for collisions between the objects with an AABB-AABB intersection.

How do I calculate an appropriate collision response to make them frictionlessly slide against each other as they collide?

# Answer
What you're looking to do is have the solid object (wall, obstacle, etc.) push back with a force equal to that which the player is exerting on it. In a simulated physical world, applying forces will not result in the behavior you want, so the velocity of the player has to be changed directly. This is what's known as an impulse.

The impulse you want to apply to the player's velocity vector is:

```
impulse = -(player.velocity * collision.normal) * collision.normal

```

Where `collision.normal` is the normal of the face of the AABB that the player is colliding with. This is simply projecting the player's velocity vector onto the face's normal, obtaining the velocity change that the AABB will enact on the player (it is negated because technically we would subtract this vector from the player's velocity, but conceptually it makes more sense to add it). Finally, add the impulse to the player's velocity:

```
player.velocity += impulse

```

And the result will be the component of the players velocity which was horizontal to the obstacle, so the player will 'slide' along the object. Note that this will work even if the player is sliding directly along the sphere, provided you calculate the collision normal correctly.

Hope this helps :)
> 7 votes

---
Tags: 3d, physics, collision-resolution, aabb
---


# Question
Title: Distributing an Android game with plugins via the market
I'm new to Android development, and was wondering how the following could be achieved within the confines of the Android market as a distribution channel:

1. One main application, which handles the main menu, networking, high scores, etc.
2. Several games which can be launched from the main menu, which all work within the same eco system. The main application is *not* just a pseudo launcher for other games, these different games will share high scores and other achievements/preferences.

In a traditional package management system such as apt, pacman or yum, this could be handled quite happily through dependencies. This does not appear to be possible via the Android market. The closest I've seen is when apps scan to check if the required app is installed, and if not, launches the market and asks the user to download the app.

This sounds like a very messy solution.

It also begs the question, would they download the game (plugin) first, which then downloads the main shell application? Or would they download the main shell application, and when they navigate to a menu item which says "Play game", then it scans for any installed games, and if none exist, redirects to the market? Also, I'm not even sure if it is possible to dig up the package from another application on the device, and start invoking classes from within (e.g. when you want to launch the game (plugin))

A final option is just to have a 3rd component which is a .jar that each game includes, which effectively contains the entire shell application. Then each game would appear to have the same menu, but it would become a nightmare as soon as you want to update the menu component and have to re-release each game. It would be especially worse if other people released games (plugins) based on the same framework and didn't update them.

Is there any other options which I haven't thought of?

Has anyone else solved this or seen a solution in any apps they've installed (doesn't have to be games)?

cheers.

# Answer
You could use the Android Intent system.

Explaining it fast: each application should have one main activity. They doesn't have to be on the same application as the launcher. The point is, when the launcher need to open another game, it send an intent to open the desired game.

With intents, you can call activities with some data from any application. You can exploit this ability to send an "MAGIC" to the game activity. That way, you can let only the launcher open the game. Also, there a thing that may be interesting to you on the Android Play Store(new Android Market), you can make an apk "not runnable". This kind of apk is not shown on the launcher. It's used often to send themes via market. I'm not sure if you can send just an activity, or an package, or a full application this way, but it worth to take a look.

Accordingly to your comment:

> Thanks, that would seem to work well once all of the apks are on the device with the main app being "runnable" and each game/plugin would be "not runnable". However, are you aware of how this would impact the install process? e.g. When you open the Play Store when neither the main app nor any games were installed, would you expect them to proceed by 1) Downloading the main app, which redirects to the Store to download more games? 2) Download games, which redirect to the Store for the main app (if not installed)? I imagine 2) is not possible if the game is "not runnable".

My answer:

Yeah, 2) is not possible. The player cant open the game, so it cant get redirected anywhere. I'm almost sure that you can't make a app need another to be downloaded(Like being unable to download apk X if apk Y isn't installed) That's why yet, some big publishers still put on their games descriptions things like "NEED ADOBE AIR" etc etc for requirements. In my view, that's all you can do for now. EDIT: I Forgot lol: 1 is totally possible. You can make your "play" button on the game turn into a "install" button if the user doesn't have the game. And make this button redirect to the Play Store
> 2 votes

---
Tags: android, architecture
---


# Question
Title: Frustum culling with an octree: one AABB per bone or one AABB per object?
I've constructed an octree for use in frustum culling. The question is, should I insert an AABB for each bone of each object, or just the one AABB for the object?

# Answer
> 6 votes
You should really just use one AABB for most objects. You could always check the object twice, first on a per-object basis and then on a per-bone basis if you want the extra precision.

---
Tags: 3d, directx, culling, frustum, octree
---


# Question
Title: What data should be cached in a multiplayer server, relative to AI and players?
In a virtual place, fully network driven, with an arbitrary number of players and an arbitrary number of enemies, what data should be cached in the server memory, in order to optimize smooth AI simulation?

Trying to explain, lets say player A sees player B to E, and enemy A to G. Each of those players, see player A, but not necessarily each other. Same applies to enemies. Think of this question from a topdown perspective please.

In many cases, for example, when a player shoots his gun, the server handles the sound as a radial "signal" that every other entity within reach "hear" and react upon.

Doing these searches all the time for a whole area, containing possibly a lot of unrelated players and enemies, seems to be an issue, when the budget for each AI agent is so small.

Should every entity cache whatever enters and exits from its radius of awareness? Is there a great way to trace the entities close by without flooding the memory with such caches?

What about other AI related problems that may arise, after assuming the previous one works well? We're talking about environments with possibly hundreds of enemies, a swarm.

# Answer
> 7 votes
There are multiple ways of doing this, but they depend on wherever you will have a large amount of interactions or a very dense population.

Unfortunately if you want your simulation to keep a good precision you will need to handle most events generated by all actors and find all/most actors requiring notification.

## Cheap area collisions

Concerning the problem with awareness areas you can solve it using simple collision detection.

In a 2d world doing collision detection on circles is "cheap". For example the operation to detect if a point is in a circle only takes 2 subtractions, 2 multiplications and an addition. You don't need to do the square root as you can store and compare the square radius of your area with the square distance directly.

If you use the 2d circle in a 3d world it will basically work as a cylinder. It can be a convenient way of creating areas if height is not very important.

## Events oriented radius

If the volume of events (firefight, movement...) is low you can try to detect each actor affected by each event. Your events will generate areas (where they can be heard).

This is the simplest method to implement, it's also the most flexible as you can pickup bullet/projectile impacts originating from actors outside of an area of awareness.

On the other hand once the volume of events increases you might have to either reduce the number of events triggering area scans or reduce the number of actors scanned per event.

**-\>** You can also create small (event) zones where all events are registered together and processed in bulks (i.e. 2 bullet impacts and a foot step happening in one zone will use only one scan and be sent to all impacted entities). **\<-**

## Actor oriented areas

You can use the "awareness area" principle. IE if an actor collides with the awareness area (circle) of another actor you simply add the colliding actor to a list of potentially interacting actors. Depending on how your engine is built, you can then register for sound messages and other events originating from the actors in the list.

To check for visual contact, you can also do your visual scans only on the list of registered actors.

You don't have to check for awareness area changes every tick. You can do it from time to time, every 5 to 30 ticks for example.

If the lists start growing you can limit them to a maximum size. But then you will have to prioritize the actors to add/exchange in the lists.

## Mixed approach

You can mix both approaches. You can register actors in awareness areas for events like foot steps, engine noses, etc... And other events (projectiles impacts, explosions, etc...) can trigger scans based on their importance. There is a much higher chance someone will hear a grenade explosion than a bullet impact, so the grenade explosion should trigger a more extensive scan than the bullet impact.

I would recommend you start implementing the event radius first. Once this one works and you are able to reduce/increase the precision of this method at will you can start implementing the actor awareness areas. This way you will be able to start moving some events to the second system.

## Context pools

Not all actors need to be notified of all events. For example an Anti-Aircraft turret doesn't need to be notified about bullet impacts and foot steps around it, even the presence of ground units could be ignored for some units.

If you find many such special cases you can create different pool of awareness areas. An actor can make his awareness area active in multiple pools. For example you might want your ground units to react to ground units only while some missile and laser equipped units could react to air units as well. Aircrafts never need to be notified about ground impacts other than explosions...

Of course you don't need to create multiple "lists" for the pools. You can simply use a bit mask and set the right mask for each actor/area. This way you can filter with a simple or before checking the distance.

## Aggregation

If you see the lists in each awareness area grow and memory is scarce you can aggregate awareness areas for groups of enemies (teams, squads, platoons, flocks, swarms...) as long as they remain close to each other. This way an entire squad can register for events or other actors/groups entering its awareness area.

Basically the group entity becomes a substitute/proxy for all scans while all members of the group are removed from the pools.

This principle can also be applied to all units inside a vehicle.

## Proximity activations

If the server is really overpopulated with bots (and you really need to keep them all alive), then you can only activate awareness/AI on those within a special "activation area around each player". This way bots (or groups) inside one or more activation area keep themselves and their awareness area activated (in the collision pool). Otherwise their awareness area is removed from the pool(s) of active areas.

The frequency at which those "activation areas" scan for "awareness areas" can vary depending on the speed of the player. A player traveling at higher speed will trigger more activations than a player camping a zone (needed at least to activate roaming bots and deactivate bots who leave the area).

Also you can deactivate a player's activation area if he boards a vehicle and assign an activation area to the vehicle if it doesn't have one. This way 10 players traveling in the same vehicle don't need to have 10 activation areas.

## Delegation

If you don't fear cheaters and other trouble makers you can delegate some of the event detection to the client application.

The server can periodically send a list of nearby actors (bots and players) which will be notified by client apps. The client application will have to do the scanning and event detection for all events generated by the player. The it can for example send the list of actors to notify about a shot, a bullet impact or foot steps.

This is an option, it can be valid depending on the kind of game you are making. This is a theoretical idea and I would not recommend doing this until you have full control over the delegated clients (bot servers or secured clients).

---

I hope this helps.

---
Tags: ai, multiplayer
---


# Question
Title: Applying effects to an existing program that uses BasicEffect
Using the finished product from the tutorial here.

Is it possible to apply the grayscale effect from here:

Making entire scene fade to grayscale

Or would you basically have to rewrite everything?

EDIT: It's doing something now, but the whole grayscale seems extremely blue. It's like I'm looking at it through dark blue sunglasses. Here's my draw function:

```
protected override void Draw(GameTime gameTime)
{
   device.SetRenderTarget(renderTarget);
   graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

   //Drawing models, bullets, etc.

   device.SetRenderTarget(null);
   spriteBatch.Begin(0, BlendState.Additive, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, grayScale);
   Texture2D temp = (Texture2D)renderTarget;
   grayScale.Parameters["coloredTexture"].SetValue(temp);
   grayScale.CurrentTechnique = grayScale.Techniques["Grayscale"];
   foreach (EffectPass pass in grayScale.CurrentTechnique.Passes)
   {
      pass.Apply();
   }
   spriteBatch.Draw(temp,
   new Vector2(GraphicsDevice.PresentationParameters.BackBufferWidth/2, GraphicsDevice.PresentationParameters.BackBufferHeight/2),
   null, Color.White, 0f, new Vector2(renderTarget.Width/2, renderTarget.Height/2), 1.0f,
   SpriteEffects.None, 0f);

   spriteBatch.End();

   base.Draw(gameTime);
}

```

Another edit: figured out what I was doing wrong. I have Blendstate.Additive in the spriteBatch.Draw() call. It should be Blendstate.Opaque, or it literally tries to add the blank blue image to the grayscale image.

# Answer
> 4 votes
Since grayscale is a post-process effect it is very easy to integrate. You just have to make sure that before drawing the scene you set a rendertarget. This means that everything is being drawn to someplace in the videocard memory and not directly to the screen. After that you save the texture you get from the rendertarget and draw that as a full screen quad with the gray-scale effect applied.

So the steps:

```
- Set rendertarget
- Draw scene
- Unset rendertarget
- Get texture from rendertarget
- Set grayscale effect
- Draw texture as full screen quad

```

This pdf should help you on your way: http://users.ece.gatech.edu/~lanterma/mpg/ece4893lec\_postprocessing.pdf .

---
Tags: xna, effects, fragment-shader
---


# Question
Title: AABB - AABB Collision, which face do I hit?
To allow my objects to slide when they collide, I need to :

* Know which face of the AABB they collide with.
* Calculate the normal to that face.
* Return the normal and calculate the impulse that to apply to the player's velocity.

**Question**

How can I calculate which face of the AABB I collided with, knowing that I have two AABB's colliding? One is the player and the other is a world object.

Here's what that looks like (problem collision circled in white):

Thank you for your help.

# Answer
> 3 votes
Check each individual plane of the AABB against the other AABB. If a plane intersects the other object's AABB, but its opposing plane does not, you know that that plane is involved in the collision. If both opposing faces intersect the other AABB, then the object is fully within the other along that axis, and the direction of collision is ambiguous/undefined.

Practically speaking, these are the same checks used to determine if AABBs collide, so you should be able to determine which faces collide as you do the AABB collision check with little additional cost.

Looking at the example, we see that:

* The sphere's yz+ plane intersects the prism, but yz- does not. Sphere yz+ collides. In a similar manner, the prism's yz- collides.
* Both the prism xy- and xy+ are within the sphere's xy- and xy+. The prism is fully within the sphere in the z direction; collision is ambiguous.
* Both the prism xz- and xz+ are within the sphere's xz- and xy+. The prism is fully within the sphere in the y direction; collision is ambiguous.

So, in this example, we detect a collision between the sphere yz+ and the prism yz-.

The normals of all faces should be obvious (yz+ has (1,0,0), yz- has (-1,0,0), xz- has (0,-1,0) ...) In general, if a quad has the vertices (a, b, c, d) in counter-clockwise order, then your can compute the normal with (b-a).cross(c-b)

Note that this problem does present the possibility of multiple collisions: depending on positioning, you can have collisions in all three axes. I think this 'ambiguity' is pretty inherent, and how you resolve it is really up to you. You might just take the average of the individual normals. You could find the area of intersection in each plane, and then choose the normal which corresponds to the largest area, or use the areas to weight the average of normals. You could find the intrusion depth along each axis, and pick the normal corresponding to the shallowest (or deepest) intrusion. Etc, etc.

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


# Question
Title: Bukkit inventory saving: crashing somewhere
I'm working on a command for a bukkit plugin that lets you transfer worlds. In the section about saving the player's inventory, I'm getting a runtime error. My question is: Why is the error happening, and how can I prevent it?

### The plugin code

```
        public void savePlayerInv(Player p, World w){
        File playerInvConfigFile = new File(plugin.getDataFolder() + File.separator + "players" + File.separator + p.getName(), "inventory.yml");
        FileConfiguration pInv = YamlConfiguration.loadConfiguration(playerInvConfigFile);
        PlayerInventory inv = p.getInventory();
        int i = 0;

        for (ItemStack stack : inv.getContents()) {
            //increment integer
            i++;
            String startInventory = w.getName() + ".inv." + Integer.toString(i);

            //save inv
            pInv.set(startInventory + ".amount", stack.getAmount());
            pInv.set(startInventory + ".durability", Short.toString(stack.getDurability()));
            pInv.set(startInventory + ".type", stack.getTypeId());
            //pInv.set(startInventory + ".enchantment", stack.getEnchantments());
            //TODO add enchant saveing
        }

        i = 0;
        for (ItemStack armor : inv.getArmorContents()){
                i++;
                String startArmor = w.getName() + ".armor." + Integer.toString(i);

                //save armor
                pInv.set(startArmor + ".amount", armor.getAmount());
                pInv.set(startArmor + ".durability", armor.getDurability());
                pInv.set(startArmor + ".type", armor.getTypeId());
                //pInv.set(startArmor + ".enchantment", armor.getEnchantments());
        }

        //save exp
        if (p.getExp() != 0) {
                pInv.set(w.getName() + ".exp", p.getExp());
        }
    }

```

### The offending line

The stack trace complains about line 130, which is this line.

```
pInv.set(startInventory + ".amount", stack.getAmount());

```

### The stack trace

```
2012-03-21 13:23:25 [SEVERE] null
org.bukkit.command.CommandException: Unhandled exception executing command 'wtp' in plugin Needs v1.0
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:42)
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:166)
at org.bukkit.craftbukkit.CraftServer.dispatchCommand(CraftServer.java:461)
at net.minecraft.server.NetServerHandler.handleCommand(NetServerHandler.java:818)
at net.minecraft.server.NetServerHandler.chat(NetServerHandler.java:778)
at net.minecraft.server.NetServerHandler.a(NetServerHandler.java:761)
at net.minecraft.server.Packet3Chat.handle(Packet3Chat.java:33)
at net.minecraft.server.NetworkManager.b(NetworkManager.java:229)
at net.minecraft.server.NetServerHandler.a(NetServerHandler.java:112)
at net.minecraft.server.NetworkListenThread.a(NetworkListenThread.java:78)
at net.minecraft.server.MinecraftServer.w(MinecraftServer.java:554)
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:452)
at net.minecraft.server.ThreadServerApplication.run(SourceFile:490)
    Caused by: java.lang.NullPointerException
at com.devoverflow.improved.needs.commands.CommandWorldtp.savePlayerInv(CommandWorldtp.java:130)
at com.devoverflow.improved.needs.commands.CommandWorldtp.onCommand(CommandWorldtp.java:60)
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:40)
... 12 more

```

# Answer
> 2 votes
I have seen this before and I am pretty sure that its because you are getting every item in inventory *including* the empty ones which return null. `inv.getContents()` gets everything. Add an if statement inside your for loop to check that they arent null before doing anything with the item.

---
Tags: java, minecraft-modding, bukkit
---


title: How to properly scroll a 2D tilemap?

text:
# Question
Title: How to properly scroll a 2D tilemap?
Hello and I'm trying to make my own game engine in Java. I have completed all the necessary ones but I can't figure it out with the TileGame class. It just can't scroll. Also there are no exceptions. Here I'm listing the code.

TileGame.java

```
@Override
public void draw(Graphics2D g) {
    if (back!=null){
        back.render(g);
    }
    if (follower!=null){
        follower.render(g);
        follower.draw(g);
    }
    for (int i=0; i<actors.size(); i++){
        Actor actor = actors.get(i);
        if (actor!=follower&&getVisibleRect().intersects(actor.getBounds())){
            g.drawImage(actor.getAnimation().getFrameImage(), actor.x - OffSetX, actor.y - OffSetY, null);
            actor.draw(g);
        }
    }
}

/**
 * This method returns the visible rectangle
 * @return The visible rectangle
 */
public Rectangle getVisibleRect(){
    return new Rectangle(OffSetX, OffSetY, global.WIDTH, global.HEIGHT);
}

@Override
public void update(){
    if (follower!=null){
        if (scrollHorizontally){
            OffSetX = global.WIDTH/2 - Math.round((float)follower.x) - tileSize;
            OffSetX = Math.min(OffSetX, 0);
            OffSetX = Math.max(OffSetX, global.WIDTH - mapWidth);
        }
        if (scrollVertically){
            OffSetY = global.HEIGHT/2 - Math.round((float)follower.y) - tileSize;
            OffSetY = Math.min(OffSetY, 0);
            OffSetY = Math.max(OffSetY, global.HEIGHT - mapHeight);
        }
    }
    for (int i=0; i<actors.size(); i++){
        Actor actor1 = actors.get(i);
        if (getVisibleRect().contains(actor1.x, actor1.y)){
            actor1.update();
            for (int j=0; j<actors.size(); j++){
                Actor actor2 = actors.get(j);
                if (actor1.isCollidingWith(actor2)){
                    actor1.collision(actor2);
                    actor2.collision(actor1);
                }
            }
        }
    }
}

```

but the problem is that all the actors are working, but it just won't scroll. Help Please.. Thanks in Advance.

# Answer
> 13 votes
Hopefully you have solved this yourself by now, if not here is some help to get you there.

# Debugger

That program you're using to type all your code in to? It's not just for typing code in and pressing "play". It's an IDE (Integrated Development Environment). This means it contains many tools to help you develop, one of those tools is the debugger. I suggest you read more about debuggers here.

## How do you use the debugger?

It's going to depend on your IDE of choice (they likely contain very similar debuggers, but just go with it). For Java there are a few major ones: Eclipse, Netbeans and more. Regardless they all have some similar features. One of the most powerful features is **breaking**, breaking can happen automatically from an exception (as I'm sure you've seen), or it can happen manually via the use of **breakpoints**. For situations like yours, breakpoints are your best friend. They will allow you to stop execution of your code at a specific point, and examine the state of your program at that time.

## How do you use breakpoints?

Again, this is IDE specific. Commonly it's a right click off to the left side column of the code window and selecting "Enable breakpoint". Yes, it's that easy. After setting a breakpoint, you'll start your program in debug mode. This mode lets the IDE know that it should pay attention to breakpoints and other debug features. Now, when the code execution gets to the point in your code where you set your breakpoint, it stops, and turns control over to you. **This is awesome.** You can now view what variable values are, many IDEs let you execute code snippets to see their result against the current state of your program, change values and more! This is SO powerful. Breakpoints rock.

Now that your program execution has stopped, it's not dead. It's waiting for you to tell it what to do next. Again, you have some powerful options. You can continue execution as normal, you can step into functions, step out of functions or step over line by line. Amazing. It's often useful to set a breakpoint at the beginning of a function, then step through the code line by line, seeing the variables change and following the execution of the code. The line by line stepping is by far the coolest way to follow the execution of your program.

Now, I hope you've read the above, followed some of the links, and looked up how to perform the actions described using your IDE of choice. If you've gotten this far, I'll offer you a further hint. Set a breakpoint on this line: `if (follower!=null){` check your values. Is follower `null`? How about `scrollHorizontally` and `scrollVertically`, are they both `true`? Now, step line by line, watch how your `OffsetX` and `OffsetY` values change as you change them around, around in a full circle ;)

---
Tags: 2d, java, tilemap
---


# Question
Title: Projective texture and deferred lighting
In my previous question, I asked whether it is possible to do projective texturing with deferred lighting. Now (more than half a year later) I have a problem with my implementation of the same thing. I am trying to apply this technique in light pass. (my projector doesn't affect albedo). I have this projector View a Projection matrix:

```
Matrix projection = Matrix.CreateOrthographicOffCenter(-halfWidth * Scale, halfWidth * Scale, -halfHeight * Scale, halfHeight * Scale, 1, 100000);
Matrix view       = Matrix.CreateLookAt(Position, Target, Vector3.Up);

```

Where `halfWidth` and `halfHeight` is are half of the texture's width and height, `Position` is the Projector's position and `target` is the projector's target. This seems to be ok. I am drawing full screen quad with this shader:

```
float4x4 InvViewProjection;

texture2D DepthTexture;
texture2D NormalTexture;
texture2D ProjectorTexture;

float4x4 ProjectorViewProjection;

sampler2D depthSampler = sampler_state {
    texture = <DepthTexture>;
    minfilter = point;
    magfilter = point;
    mipfilter = point;
};

sampler2D normalSampler = sampler_state {
    texture = <NormalTexture>;
    minfilter = point;
    magfilter = point;
    mipfilter = point;
};

sampler2D projectorSampler = sampler_state {
    texture = <ProjectorTexture>;
    AddressU  = Clamp;
    AddressV  = Clamp;
};

float viewportWidth;
float viewportHeight;

// Calculate the 2D screen position of a 3D position
float2 postProjToScreen(float4 position) {
    float2 screenPos = position.xy / position.w;
    return 0.5f * (float2(screenPos.x, -screenPos.y) + 1);
}

// Calculate the size of one half of a pixel, to convert
// between texels and pixels
float2 halfPixel() {
    return 0.5f / float2(viewportWidth, viewportHeight);
}

struct VertexShaderInput {
    float4 Position : POSITION0;
};

struct VertexShaderOutput {
    float4 Position :POSITION0;
    float4 PositionCopy : TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input) {
    VertexShaderOutput output;
    output.Position = input.Position;
    output.PositionCopy=output.Position;
    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 {
    float2 texCoord =postProjToScreen(input.PositionCopy) + halfPixel();

    // Extract the depth for this pixel from the depth map
    float4 depth = tex2D(depthSampler, texCoord);
    //return float4(depth.r,0,0,1);
    // Recreate the position with the UV coordinates and depth value
    float4 position;
    position.x = texCoord.x * 2 - 1;
    position.y = (1 - texCoord.y) * 2 - 1;
    position.z = depth.r;
    position.w = 1.0f;

    // Transform position from screen space to world space
    position = mul(position, InvViewProjection);
    position.xyz /= position.w;
    //compute projection
    float3 projection=tex2D(projectorSampler,postProjToScreen(mul(position,ProjectorViewProjection)) + halfPixel());
    return float4(projection,1);
}

```

In first part of pixel shader is recovered position from G-buffer (this code I am using in other shaders without any problem) and then is tranformed to projector viewprojection space. Problem is that projection doesn't appear. Here is an image of my situation:

The green lines are the rendered projector frustum. Where is my mistake hidden? I am using XNA 4. Thanks for advice and sorry for my English.

**EDIT:**

Shader above is working but projection was too small. When I changed the Scale property to a large value (e.g. 100), the projection appears. But when the camera moves toward the projection, the projection expands, as can bee seen on this YouTube video.

# Answer
> 5 votes
In your shader, you'll need to remove the `position.xyz /= w;` as this is what is causing your resizing issue:

```
// Transform position from screen space to world space
position = mul(position, InvViewProjection);
position.xyz /= position.w;  <<-- Comment this out

```

That should do the trick.

# Answer
> 0 votes
If you get results that are too small and get to that size it might be because the frustum is still in 1 to -1 space or 0 to 1 or the like? Is that your origo that the frustum is based around?

---
Tags: c#, xna-4.0, shaders, deferred-rendering
---


# Question
Title: How is constant buffer allocation handled in DX11?
I'm starting with DX11 and I'm not sure if I'm doing the things right. I want to have both pixel and vertex shader program in one file. Both use some shared and some different constant buffers. So it looks like this:

Shader.fx

```
cbuffer ForVS : register(b0)
{
    float4x4 wvp;
};

cbuffer ForVSandPS : register(b1)
{
    float4 stuff;
    float4 stuff2;
};

cbuffer ForVS2 : register(b2)
{
    float4 stuff;
    float4 stuff2;
};

cbuffer ForPS : register(b3)
{
    float4 stuff;
    float4 stuff2;
};

....

```

And in code I use

```
mContext->VSSetConstantBuffers( 0, 1, bufferVS);
mContext->VSSetConstantBuffers( 1, 1, bufferVS_PS);
mContext->VSSetConstantBuffers( 2, 1, bufferVS2);

mContext->PSSetConstantBuffers( 1, 1, bufferVS_PS);
mContext->PSSetConstantBuffers( 3, 1, bufferPS);

```

The numbering of buffers in PS is what bugs me, is it alright to bind random slots to shaders (in this example 1 and 3)? Does that mean it still uses just two buffers or does it initialize 0 and 2 buffer pointers to empty?

Thank you.

# Answer
> 1 votes
Yes, I'm pretty sure it's fine to leave any unused slots unbound. Internally what happens is likely that the constant buffer pointers get put in a little array that the shader can load from, so all that will happen is some entries of that array will be NULL, but since the pixel shader doesn't read them it doesn't matter.

---
Tags: c++, directx
---


# Question
Title: Targeting a vehicle with complex movement?
Targeting a vehicle with known constant velocity is simple, and collision is guaranteed (see Predicting enemy position in order to have an object lead its target, Find meeting point of 2 objects in 2D, knowing (constant) speed and slope). Imprecise AI can be modeled by adding a small error factor.

But how would one go about targeting a vehicle whose movements are more complex? Perhaps it's evading the AI or another game object.

I've been thinking about how I'd do it myself in a FPS (in which bullets have finite speed) and think there might need to be at least couple of targeting modes based on the target's movement in the previous second or so:

* If it's near linear (peak acceleration in a certain range) target with the linear model
* If it's highly irregular (perhaps size of bounding box of recent positions could be used?) , target at an average

For now I can assume 2d space, AI is stationary and projectile is unguided and moves linearly.

# Answer
Random thoughts (no code)...

In real life, one targets a vehicle with complex movement by trying to figure out what that movement is so as to anticipate it. If you are writing code for AI to target AI, then you should create a targeting AI that is derived from the target AI. For example, if your target will run for cover if near by, the targeting AI should be able to anticipate this movement.

On the other hand if you are trying to target humans with AI, it's going to be a lot more difficult. Random targeting could work, but may look just "random", which may or may not be an issue for your game.

To come up with a solution, one thing you can do is mentally separate out the problem into the different pieces of trying to shoot something...

**Tracking Ability**

In order to hit a target with an aimed device that can move, one must be able to track and move the device to follow the target. The targeter observes the target moving, and moves their aim to follow. If a tracker has a limited amount of movement, then its tracking ability will be hampered and it may have a hard time tracking some things. but if the tracker has a large amount of tracking freedom, it can potentially track many things. Think about the difference between a tank turret and you pointing at something with your finger.

**Tracking Speed**

Another factor is how fast the tracker can track. If it is very slow (think "tank turret"), then it can't track a target that moves fast. Instead it has to rely on anticipation of the target's path. On the other hand a tracker with "fast" speed can quickly move to a target's new location.

**Tracking Reaction Time**

A third factor in tracking is the reaction time of the tracking. That is, when the target changes direction, how fast can the tracker react? The ultimate tracker is one with fast tracking speed and instant reaction time - it can track any change.

**Target Recognition**

How well can the targeter recognize a target? If one is tracking a target in a complex environment, there may be times when the targeter fails to recognize or "loses" the target. The faster the targeter can recognize a target, the better it will do. The less likely it is to lose a target, the better it will do.

**Shooting Reaction Time**

Just because the target shows up in the crosshair for a brief moment of time doesn't mean that a shot will happen. Can the tracker react fast enough to pull the trigger? Really bad trackers with really bad reaction time won't hit anything. Really good trackers with really good reaction time will hit anything, because they only need the slightest bit of time on target.

**Anticipating Movement**

Anticipation of movement is another factor. This is the difference between just trying to track to where the target is now, versus tracking to where you think the target will be. If a tracker can anticipate, they can track the target better, and get more chances to have the target in the crosshairs, and thus improve their ability to get a shot off based on their reaction time. Zero anticipation trackers would just automatically move the aim towards the target, irrespective of the target's actions. The worst case is a tracker who's speed is slow with no anticipation trying to track a simple moving target. Imagine a target that just steps to the left and then to the right every few seconds. A slow tracker would just keep bouncing the aim back and forth, never fast enough to get the target. Only if the target stopped moving could the tracker hit it, and only then if the stop was long enough for the reaction time.

**Modelling Target Movement**

As mentioned up top, the tracker can anticipate the target by modelling its movement, which is not necessarily that hard to do. If a vehicle is driving at some speed, there are a finite number of places that vehicle can be in the next second, and they are laid out essentially like a triangle in front of their movement. The faster they are going, the tighter the triangle is. The faster they can turn, the wider it is. A really fast vehicle that can hardly turn (like a rocket) has a very small narrow potential path. A slow one that can turn very well has a much wider potential path. It's like those backup cameras on some cars that overlay lines showing you where your car will go if you keep driving as it is now, plus where you potentially could go if you were to turn the wheel more.

So with that in mind, you should put your "potential target space" box in that potential path space. If you know your target has a tendency to veer from side to side, your target box needs to be wide enough to encompass all possible movements. If your target is pretty linear in their movement, you can make your target box much smaller and centered on the anticipated location of movement. I think this kind of thinking will help you make a single solution to tracking that doesn't really differentiate between linear and non linear anticipation. Linear tracking is simply anticipation with a higher level of confidence (smaller targeting box), while random tracking is low level confidence tracking (larger tracking box).

Of course this gets challenging if the target is standing still, because it has the potential to move in any direction. But of course if it sits still too long, it's an easy target even for the slowest tracker.

**Target Psychology**

Consider what you would do if you suddenly had shots landing to your left. Would you run at them? NO! You'd run to the right. Or maybe you'd run for cover. But then maybe the targeter specifically shoots at the cover location so then you don't run for it.

**Capacity to Learn**

Potentially your targeter can learn from experience. Suppose at first they have no idea of the vehicle's potential movement. They don't know how fast it can go, or how fast it can turn. Observing it in action though will teach them what this is. Meaning that the first time they try and track one, they may not do very well. But they learn the movement behavior, and do better on subsequent tries.

**Further Reading**

A bit of googling after writing this led met to this manual for rifle marksmanship...

http://www.globalsecurity.org/military/library/policy/army/fm/3-22-9/c07.htm

Might be some ideas in there about how a real person would/should/could aim and track.
> 11 votes

---
Tags: ai, aiming
---


# Question
Title: Drawing a texture line between two vectors in XNA WP7
I want to create a simple graph maker in WP7.

The goal is to draw a texture line between two vectors what the user defines with touch. I already made the rotation, and it is working, but not correctly, because it doesn't calculate the line's texture height, and because of that, there are too many overlapping textures. So it does draw the line, but too many of them.

How could I calculate it correctly?

Here is the code:

```
public void DrawLine(Vector2 st,Vector2 dest,NodeUnit EdgeParent,NodeUnit EdgeChild)
    {
        float d = Vector2.Distance(st, dest);
        float rotate = (float)(Math.Atan2(st.Y - dest.Y, st.X - dest.X));
        direction = new Vector2(((dest.X - st.X) / (float)d), (dest.Y - st.Y) / (float)d);
        Vector2 _pos = st;
        World.TheHive.Add(new LineHiveMind(linetexture, _pos, rotate, EdgeParent, EdgeChild,new List<LineUnit>()));
        for (int i = 0; i < d; i++)
        {
            World.TheHive.Last()._lines.Add(new LineUnit(linetexture, _pos, rotate, EdgeParent, EdgeChild));
            _pos += direction;

        }
    }

```
* d is for the Distance of the st (Starting node) and dest (Destination node)
* rotate is for rotation
* direction calculates the direction between the starting and the destination node
* \_pos is for starting position changing

Thanks for any suggestions/help!

# Answer
I'm not sure I understood what your problem is, but here's how I do it. First I create a static class on my project to provide an extension method for `SpriteBatch` that lets it know how to draw textured line. Example (just the class, it's missing the using directives and the namespace so place it wherever you want):

```
public static class LineRenderer
{
    public static void DrawLine(this SpriteBatch spriteBatch, Texture2D texture, Vector2 start, Vector2 end)
    {
        spriteBatch.Draw(texture, start, null, Color.White,
                         (float)Math.Atan2(end.Y - start.Y, end.X - start.X),
                         new Vector2(0f, (float)texture.Height / 2),
                         new Vector2(Vector2.Distance(start, end), 1f),
                         SpriteEffects.None, 0f);
    }
}

```

The texture passed to the method should have size `1xN` where `N` is the thickness of my ine. I'll give an example further below but first an usage example:

```
spriteBatch.Begin();
spriteBatch.DrawLine(lineTexture, new Vector2(20, 20), new Vector2(120, 120));
spriteBatch.DrawLine(lineTexture, new Vector2(120, 20), new Vector2(220, 60));
spriteBatch.DrawLine(lineTexture, new Vector2(20, 240), new Vector2(220, 100));
spriteBatch.End();

```

Which gives the following result (using the texture on the right side which I zoomed in for clarity):
> 4 votes

# Answer
I think you are mixing up your logic and drawing code too much. Separate your node linking and line creating.

Basically it looks like you want to draw a "thick" textured line between two points on screen. Here's some pseudo code that shows you how to get all the vertices for doing just that:

```
DrawThickLine(Vector2 startP, Vector2 endP, float width) {
    float dx = startP.x - endP.x;
    float dy = startP.y - endP.y;

    Vector2 rightSide = new Vector2(dy, -dx);
    if (rightSide.length() > 0) {
        rightSide.normalise();
        rightSide.scale(width / 2);
    }

    Vector2 leftSide = new Vector2(-dy, dx);
    if (leftSide.length() > 0) {
        leftSide.normalise();
        leftSide.scale(width / 2);
    }
    Vector2 one = leftSide + startP;
    Vector2 two = rightSide + startP;
    Vector2 three = rightSide + endP;
    Vector2 four = leftSide + endP;

    DrawQuad(one,two,three,four);
 }

```
> 0 votes

---
Tags: xna-4.0, vector, windows-phone-7
---


# Question
Title: With an iPhone game, can I allow music from other apps to play while my game is being played?
My game doesn't have any music but it does have sound effects. Right now if I power up Pandora and then start a song and then switch to my game it will stop the Pandora song. Is there a special way I need to play my sound fx so that the music from Pandora will keep playing while my game is running?

# Answer
If you set up your Audio Session type to `AVAudioSessionCategoryAmbient` you'll get mixing with whatever's playing in the background:

http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioSession\_ClassReference/Reference/Reference.html#//apple\_ref/c/data/AVAudioSessionCategoryAmbient
> 3 votes

---
Tags: iphone, music, sound-effects
---