# Question
Title: Game Development In C Only. Is it possible?
I am a first year college student in India and want to make a small game as a this semester project.

I am quite good at C and am learning it rapidly but I wanted to ask if developing a game entirely in C (no C++ or C#) I'd love to use these but for college projects, we have strict requirements of using only C.

What I am looking for is a simple top view driving game. It won't have anything fancy and even the visual things will be powered by simple characters. For example, user controlled car can be represented by ▓ and edges of road by series of |'s. What do you think?

# Answer
> 25 votes
Writing games in C is possible. For example, Quake II is written purely in C, so writing other games in C should be no problem at all. It may be the better choice if you're more proficient and comfortable in C than in C++.

# Answer
> 13 votes
I work on a AAA MMORPG codebase that is pure C, so yes.

# Answer
> 6 votes
Yes, it's perfectly possible. Many OS-level APIs like POSIX and Windows, DirectX and OpenGL all have C-compatible interfaces.

# Answer
> 6 votes
Fabien Sanglard has written an article about his 3d engine in C. On reddit, this article has created an interesting debate.

Languages are only tools... So use them wisely. To create a good game, it can be easier to use XNA or Unity3D. Mastering C is a good first step, but you must learn C++, D, python, lua ... C++ is a very difficult langage. So use it carefully.

# Answer
> 3 votes
C is great for game development.

I'm working on a 3D platformer, and I've never had any problems with the language. The only problems are collision detection and shading, I just know nothing about them, they would still occur in any other language.

In fact, I find it much easier than languages like C# and Java. I always iterate on entities using pointers (an example from my code), and `fread` saved a lot of time making the map loader.

If you want object orientation and modularity, you can make structures of function pointers.

# Answer
> 1 votes
Without a doubt. A lot of libraries useful in game development (such as SDL, PhysFS, etc...) have C APIs, which helps a lot.

You may wish to look into embedding a scripting language such as lua if you wish to do any extensible, high-level programming. Many people are beginning to see the appeal in programming a C framework that uses lua for things such as AI, events, etc...

Good luck.

# Answer
> 1 votes
Simple answer for this question is: You can do simple text based game like this in every programing language. Even pascal, basic or x86 assembler :\]

(and do not need anything else)

# Answer
> 0 votes
Yes it is possible, but it may not be the most desirable course of action. A number of people recognize these days that C and C++ both aren't ideal for a number of tasks, and high level game logic often falls into that category.

If you insist on C instead of C++ (which makes no sense to me, but to each their own), you may be best off using Lua in conjunction with C.

For your college projects that require C this won't be an option, but for spare time projects it would be a good way to learn.

# Answer
> 0 votes
Of course you can. Many games have been programmed in C (DOOM comes to mind). SDL is a game programming library written in C.

Of course, it may be a little more difficult than using C++ for a big project, but it's possible.

# Answer
> 0 votes
I think it is possible to make a complete c games. I have made a game ( which is similar to 'space impact' of nokia 1110 mobile ) in my 2nd semester project using turbo c compiler. I think you can try this way ( as a first year college student ) without knowing any others.

---
Tags: c
---


# Question
Title: Cocos2d patterns for simple texture management
I'd like to simplify the way I preload image resources in my Cocos2d based iOS apps. I've created a small object the just wraps a few of CCTextureCache's methods. It looks like this:

```
@interface TextureHelper : NSObject
+ (void) preloadTextures;
+ (CCTexture2D *) textureForImageNamed:(NSString *) imageName;
@end

@implementation TextureHelper
+ (CCTexture2D *) textureForImageNamed:(NSString *) imageName {
    return [[CCTextureCache sharedTextureCache] textureForKey:imageName];
}

+ (void) preloadTextures {
    // or could read from a directory...
    NSArray *imageNames = @[
    @"myImage1.png",
    @"myImage2.png"
    ];

    for (NSString *imageName in imageNames)
        [[CCTextureCache sharedTextureCache] addImage:imageName];
}
@end

```

The goal is to preload all images at start-up. Then during game play any sprites created on the fly won't cause images to be read from disk. **What are some other more common and/or more effective patterns for achieving this?**

# Answer
> 1 votes
I think that the answer to this question is quite dependent on the structure of your game (level based? infinite runner?)

However in general in my experience you don't want to load ALL of your textures at startup. There are a few reasons for this:

1. The iOS application sandbox only allows a certain amount of RAM to be used and once you reach that threshold, any more texture loaded kicks out other textures out of RAM (cocos2d manages this for you I believe.) However in the worst case the application will crash if it does not have enough memory to run. So load only the textures you immediately need.
2. You're holding a lot of unused textures in memory which is inefficient.
3. iOS WILL clear your game out of RAM if it needs it. So if your game has a lot of textures loaded (using up a lot of RAM) and the player multi-tasks out to another memory intensive app and iOS needs more memory for that app? Your app will be killed and your memory cleared. The next time the player switches back to your app, they will start from the beginning. You can avoid this situation by not using more RAM than you really need to.
4. Cocos2d also will clear out unused textures when it receives a memory warning. You may end up faced with a situation where the textures you thought you loaded, are no longer in memory and your application will crash when trying to create a CCSprite using the texture.

I would recommend lazily loading textures as and when you need them. This also means you have to do a few things:

1. Figure out how to package your sprite sheets so they are logically separated by when you need the textures within a single sprite sheet. For example, if your game is level based or is a children book, I would bundle textures that are part of the same level or the same page together. In this case you can load "level-02-textures.png" when the player is about to finish level 01 and by the time they are at level 02, the textures are loaded and ready to be used without disrupting gameplay.
2. Figure out the best place to load your texture so it does not disrupt gameplay. Like the previous example, you know when the player will advance to a new level and therefore can start the loading process asynchronously before they need it to create an illusion of continuous gameplay without any disruption to load the textures. In the case of a book, I would have 3 pages loaded at any one time: Previous Page, Current Page, and Next Page. Anything outside that should be cleared from memory to give yourself more room.
3. Clear any textures that you are not immediately using as much as you can. This is important. If iOS determines that your application is using too much memory, it will abort the application quite brutally so get into the good habit of freeing any memory that you can. This gives you more flexibility.
4. Balance efficiency vs. flexibility. My suggestion in #1 of this list means that you may run into a decision you'd have to make. "If this texture is used in both level 1 AND level 2, should I split that into it's own sheet or lump it into the sheet with level 1 and again in level 2?" This choice affects the complexity of your code (with more than 1 file you might need per level, you'll have to have a more elaborate system of determining which texture is required for a particular level) and the space usage of your application (duplicating textures increases file size, but splitting textures also increases file size... which is worse? That depends on how complex your texture is.) The decision may be easy if a texture is only used in 2 levels, you might just bite the bullet and duplicate it in both level textures. But what if it is used in 5 levels or 10 levels? Then it would make more sense to split it out into its own sheet.

In the end of the day, as you can probably tell by now, it all really depends on your game, how many assets you have, how you organize your levels, how you designed your animations and textures, and a bunch of other factors. However, I hope this gives you a general idea of what to consider when you look at the problem of texture management.

---
Tags: textures, cocos2d-iphone, preload
---


title: How to create strength meter?

text:
# Question
Title: How to create strength meter?
I am creating game like bow and arrow. I want my hero will shoot the arrow with the strength meter, how will create the power?

# Answer
> 1 votes
The meter is simply a visual indicator of the amount of force that will be applied to the arrow when the bow is released. How you display that number is going to be specific to the style of your game and what you're using for the GUI.

Choosing the amount of force will also be dependent on how you want the game to work. A simple method would be to slowly increase a value to the maximum amount, as long as the user holds the fire key. When the fire key is released, the value generated is used and applied to the arrow as a force in the direction the arrow is pointing.

---
Tags: box2d, cocos2d
---


# Question
Title: Alternative to JSF for browser-based 4X game
I intend to make browser based MMO game. Something from Master of Orion genre but with more accent on command ship operations.

I've done some tests and research and turns out that indeed, for dictionary type data (like technology tree nodes, inventory items, mission definitions) the XML files seem best approach. But there will be whole lot of them and they are inter-dependent so performance-wise there is no option to load them on each HTTP request.

I want system where application starts, loads definitions to dictionaries from XML and keeps it in memory for the whole time the application works. Application awaits requests and responds them with XHTML using the dictionary data from array/collection kept in memory. All the other data like players' data, alliances' data etc. comes normally from relational DB. I think this model would put much less strain on DB and whole application would be much less resource-hungry.

So PHP I know and used is not an option, right?. Is my only option some Java server technology like JSF? I coded in Java previously, but it was Java SE and it didn't make good impression on me. So are there alternatives? If not what specific Java server technology would be most suited?

# Answer
As far as I can see, you should be able to load your resources once and then keep them in memory.

It's unclear from your question whether you're talking about the client or server - but I'll assume server (JSF is presumably used in a HTTP server here?)

Surely it is possible to create a shared data structure which can be used by multiple threads.

Alternatively, do you need to load these data structures each request? Can you not simply load them on-demand?
> 0 votes

---
Tags: java, architecture, browser-based-games
---


# Question
Title: Computing orbit direction depending on angle of approach
I'm trying to develop a simple 2D space game with no friction using . In the game, I have several planets which all applies forces to the player according to Newton's law of universal gravitation. Once the player is close enough to a planet, I need to put him in orbit. I do so, by creating a pivot joint between the planet and the player. From the player's liner velocity, I compute the joint's motor speed in order to achieve an as much as possible smooth cyclic rotation around the planet.

The solution, which might not be optimal (*in future versions I would like to avoid completely the joint*), so far is working but I'm not able to determine correctly the joint's rotation direction. The rotation of the player around the planet should be CW or CCW depending on the player's angle of approach. How do I compute that ?

Thanks !

# Answer
> 1 votes
I'd construct a line from the centre of the planet to the ship, and also calculate a point which is the ship's position + ship's velocity.

From there you can use a standard test to find out which side of the line the point is on, which tells you if it should orbit clockwise or anticlockwise.

---
Tags: 2d, orbit
---


# Question
Title: Where can I find an open source component-based game?
Check that link: Evolve Your Hierarchy

I'm interested in that kind of game development, and the theory looks nice! But I want taking a look in the source code of some game developed following that methodology. It will be good if it's simplistic (or even educational!), and better if it's coded C++ or C#. Thanks!

# Answer
> 1 votes
As Byte56 points out, there are a lot of articles on the web discussing this topic. It's been a highly debated and discussed game developer topic for years now and probably will be for more years to come.

The reason why its still such a hot ticketed concept is because there really isn't a tried and true **roadmap** that describes how to manage, store, and relate entities and components. Just when you think you have a strategy on how you'll go about it, the next article you read may approach it from an entirely different angle, leaving you proposing some mixin or alternative all together.

My advice is to start small and simple. Don't try to design an Entity Component System with all the bells and whistles, just concentrate on a just a few specific features you want to try and explore. Tweak the design and don't be afraid to rewrite it if needed. Such a system can quickly evolve and as you add more behaviors and features, you'll find the need for more and more bells here and there which often require tweaks or even major changes.

---
Tags: component-based
---


title: Moving player in Box2d without forces

text:
# Question
Title: Moving player in Box2d without forces
How do I move player with keyboard without applying forces? If I do `playerBody.setLinearVelocity(new B2Vec2(0, 2))` it moves the player but when I release the key for movement, the ball is continuously moving for few seconds.

# Answer
Applying a force still the way to do it. But instead, you can apply directly the impulse for the desired speed. You can still make the player instantly stop (instead of decelerating) You just need to set the desired speed to zero. Here's the snippet:

```
b2Vec2 vel = body->GetLinearVelocity();
float desiredVel = 0;
switch ( moveState )
{
  case MS_LEFT:  desiredVel = -5; break;
  case MS_STOP:  desiredVel =  0; break;
  case MS_RIGHT: desiredVel =  5; break;
}
float velChange = desiredVel - vel.x;
float impulse = body->GetMass() * velChange; //disregard time factor
body->ApplyLinearImpulse( b2Vec2(impulse,0), body->GetWorldCenter() );

```

If you want gradual acceleration, change the switch block by:

```
  case MS_LEFT:  desiredVel = b2Max( vel.x - 0.1f, -5.0f ); break;
  case MS_STOP:  desiredVel = 0; break;
  case MS_RIGHT: desiredVel = b2Min( vel.x + 0.1f,  5.0f ); break;

```

You should be fine with this.

Source: http://www.iforce2d.net/b2dtut/constant-speed
> 2 votes

# Answer
Depending on what you want to do, you can use

```
playerBody.setPosition(new b2Vec(x,y))

```

so while you have your key pressed down you can keep increasing your position by 1 or something.

or when the key is down you can apply the linear velocity and when the key is up you can set the linear velocity and to 0.

The velocity will always be moving the body until the forces in the world acting against the reduce the velocity to 0;
> 0 votes

---
Tags: box2d, actionscript-3, movement
---


# Question
Title: How do I spawn enemies with a delay using threads?
Right now I have this:

```
Thread enemySpawner = new Thread(new Runnable() {
    public void run() {
        if(world.getCurrentState() == gameState.GAME) {
            world.spawnEnemy(x, y);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
});
enemySpawner.start();

```

It is called in the constructor of my game. For some reason, only one enemy spawns. How do I fix this?

# Answer
> 3 votes
You need to enclose the spawning code in a loop, i.e.

```
Thread enemySpawner = new Thread(new Runnable() {
    public void run() {
        while(world.getCurrentState() == gameState.GAME) { // Just changed it to a while loop
            world.spawnEnemy(x, y);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
});
enemySpawner.start();

```

Threads don't run over and over again; you have to implement the loop logic yourself.

---
Tags: java, lwjgl
---


title: Game-components and memory management

text:
# Question
Title: Game-components and memory management
I'm stitching together the workings of a component based game engine, and as such have been deeply reading into many aspects of both game engine architecture and a fair amount of opinionated theory of different programming styles / do's and dont's. Etc.

Currently, I really like the idea of treating components like little data structures and having larger sub-systems handle this data appropriately. Thus the "GameObject" is more of a GUID that ties in these struct-based components into a loosely defined object with various properties.

So my question, or well current delima is how to store these various components and I seem to have two competing ideas.

* The easy way to handle storing these components, is to have each sub-system double as a factory class which creates and stores the component into a hash table which the sub-system maintains. So the `Renderer` would have a method that could produce and store a `Renderable` component given a GUID and some input parameters. Whenever a object or object component is removed from game each sub-system could be messaged and that sub-system could then delete the corresponding component without trouble.

In addition to that, components of the same type are grouped together and since these components are all the same size this makes for a pretty damn clean memory management. I see no problem using std::vector or a hash table of some sort to contain these elements.

The issue I have with this approach is that it fragments a (all) "GameObject's" significantly. Suddenly the position component of a given object is located miles away from the physical component. This seems like a performance nightmare, looking up any other component becomes a cache-miss, etc. Which brings me to option #2...

* The other approach I've come up with is to keep the factory part of the sub-systems. `Renderer` would still produce `Renderables`, but `Renderer` would not be responsible for storing the component, instead it would be given a location to write the component struct to as an input parameter by a dedicated system, like a memory manager.

The advantage here is components belonging to a particular GUID could be grouped together in contiguous memory (at least in theory), providing a chance that the needed date for another component (say `Physical` wants to alter the `Position` component) may already exist in the processors cache due to the effects of cache-lines.

The (massive) disadvantage that I see in doing this is managing the necessary memory to group these differently sized components together, that sounds like a nightmare to me.

So what I wish to ask is, what do you guys think? Is there a really smart third option I haven't thought of, or am I crazy for even caring about cache-misses? In that case, is the easy way just the correct way, etc, etc.

Thanks, -Cody

# Answer
If anything, the first option might be better for cache misses since generally you'll be iterating through, say, all the `Renderable` components at once. Just copy the data you need into that component to avoid cache misses due to looking up data.

But it seems like you're suffering from design paralysis. Do you actually have a working game yet? Are the problems you're trying to solve actual problems given the scope of game (or games) you're planning on using with this tech as well as the target platforms you're hitting?

Just pick something and move forward. Benchmark if you really need to care about performance (chances are you don't). Use good design practices to keep things separated enough that you can refactor into one or the other pattern if the need arises.
> 7 votes

---
Tags: c++, component-based, memory-efficiency, gameobject
---


title: Difference between rotation methods?

text:
# Question
Title: Difference between rotation methods?
My question is in about rotate methods in `android.graphics.Camera`. In `Docs`, I saw these comments:

> public void rotateX (float deg) Since: API Level 1
> Applies a rotation transform around the X axis.
>
> public void rotate (float x, float y, float z) Since: API Level 12
> Applies a rotation transform around all three axis.

There is my question:What is difference between using `rotate (float x, float y, float z)` and a sequence of `rotate` methods? For example what's the difference between these two snippets A and B?

A)

```
camera.rotate (x, y, z);

```

B)

```
camera.rotateX (x);
camera.rotateY (y);
camera.rotateZ (z);

```

# Answer
> 3 votes
Applying a sequence of Euler (yaw/pitch/roll) rotations can have a disadvantage when compared to applying a rotation matrix or quaternion operation, which both apply the rotations simultaneously. Sequential axis transforms have the potential to suffer from gimbal lock when one step in their sequence renders a subsequent rotation meaningless. *I.e., this problem would occur if the first rotation moves the vector directly onto the axis of the second rotation, then the second rotation accomplishes nothing.* The more complex operations are immune to this problem.

Presumably, the API 12 method `public void rotate (float x, float y, float z)` is an advanced matrix or quaternion rotation. However, if it was naively implemented, it may be no better than applying the rotations in sequence. In that case, its only benefit would be reducing the number of functions you would need to call. But if it IS implemented well, then it will be faster, simpler to use, and less error prone than sequential operations.

In either case, you should use it for 3-axis rotations.

---
Tags: android, camera, rotation, html-canvas
---


title: Y Axis inverted on vertex output

text:
# Question
Title: Y Axis inverted on vertex output
I've got my project running and somehow it seems my vertex y components are inverted. 10 in the positive on Y goes down and 10 negative on the Y axis goes up.

I can't find anything with the initialization and I am not doing any negative scaling in the view matrix. I've never had something like this happen before, does anyone have some tips or things to look for ?

How I am sending verteces to the GPU ( Currently intermediate mode ) glVertex3f( x\_pos\_n, 10, z\_pos );

I am using CG in the project but even without shaders the Y axis seems to be inverted.

# Answer
> 0 votes
Came down to my quaternion class not being right. I remove it and converted it all to the GLM math library. Works like a charm now, somehow I messed up going from quaternion to my view matrix.

---
Tags: opengl, mathematics, matrix, view
---


# Question
Title: Detect touch for android....for unity 3d
i am trying to detect the touch on android and is it possible to have a same function with touch which can work same as OnMouseUp() function

# Answer
Seriously, Google that stuff:

http://docs.unity3d.com/Documentation/Manual/Input.html

There is a complete manual on unity. Took me just one google search.
> 3 votes

# Answer
if you want to develop the touch functionality you have to write input.getmousebuttondown,input.getmousebuttonup,input.getmousebutton will work.One more way also there touch pahse began,thouchphase.end. OnMouseUp() and OnMouseDown() will work only for windows,mac.It won't support for mobiles(ios and android).

check this links
> 0 votes

---
Tags: android, unity, touch
---


# Question
Title: When should you roll your own game engine?
I've been a software developer for 5 years, now, and I am wanting to get into iOS game development. I've played around with the iOS SDK for about 2 years, attending cocoaheads meetings, and I feel I have a good grasp on objective-c, cocoa and even c and c++.

I have a game idea, and know that I will use Box2D, but I'm wondering if I should use cocos2D or not. The main reasons are:

1. I may want to do things, graphics wise, that aren't available in cocos2d.
2. If I roll my own game engine, I'll have more control.

Of course, the main reason for using an already-existing game engine is the time it saves, and it makes the hard stuff easier; but for someone who has the technical chops to roll his own, does it make sense?

# Answer
> 38 votes
Most of the other posts will be "make a game not an engine", but I'm going to assume that you have a particular game in mind you want to make and want to know when it's a good idea to start with somebody else's code base or start from scratch.

**You shouldn't roll your own tech unless you *know* you need to roll your own**. That may sound flippant but it's really the only correct answer. As with most decisions, there are tradeoffs. Only you can determine for your particular situation the cost/benefit analysis.

You should have an understanding of the following things (this list is hardly all inclusive).

* What middleware is already out there that you could use ("engine" or otherwise)
* What that middleware brings to the table, feature wise.
* How mature/proven the middleware is, especially if you care about multiplatform support
* What kind of tools the middleware provides, or doesn't provide, to help speed up development (don't discount tools with your own tech)
* What limitations that middleware has (as a simple example, Unity 3.x didn't do real time shadows from dynamic lights on iOS)
* What specific features your particular game *has to have*.
* What your deadlines are, and how much time you will have to spend to get up to the point of where the middleware will get you vs. how much the middleware costs.
* How extensible the middleware is (for example, you can get around the shadow problem on iOS in Unity by using blob shadows. Or maybe projection shadows.)

(Notice that I specifically didn't put "more control" up there. That's a loaded phrase that could range from "I don't like code I don't write" to "I need to be able to see, understand, and tweak all the variables in the physics engine to achieve this particular effect." The first one isn't really a valid consideration, but the second is.)

Personally, I find that rolling your own tech for a low-budget game is hardly ever worth the effort. The amount of power you get the cheap engines these days is ridiculous. You're not at a point where you're deciding on a multimillion dollar triple A engine license or not. You're not going to be able to beat what, say, Unity offers to you for $3k. Or Cocos2d for whatever it costs (isn't it free?).

Now, if your game is mostly focused around some kind of tech that other engines can't provide, or can't provide at a reasonable framerate, then it might be worth investigating what you can do. That doesn't mean you throw out the other middelware entirely, though. Just because you need your own, say, renderer, doesn't mean you can't use some other middleware for physics or sound or UI or what have you.

# Answer
> 14 votes
Don't roll you own engine. Roll you own game. If you happen to write an engine at the same time then good for you, if not you can always refactor whatever parts you might want to reuse to make it more "engine" like.

People often over estimate what it takes to write the "engine" part of a game. If you only do what you need it won't take that long. The hard part is to not get stuck writing infrastructure and to only write what you absolutely must to solver your problem.

I would use an existing engine when:

* I have a tight deadline
* I have a known fixed feature set so that I can chose an engine for that

# Answer
> 3 votes
I think you should just write your game, and perhaps you'll end up with an engine later. Writing the graphics engine (which is all it sounds like you're talking about) from scratch using nothing but OpenGL is likely only going to waste your time. It is a relatively well-solved problem so generally you'd only be changing the shape of the API without adding much in the way of significant new features relative to any other available third-party solution out there.

If Cocos2D or some other graphics layer meets your requirements now, then use it. If your requirements change during development, you can swap out the rendering back end relatively easily -- if you truly believe you have the experience and wherewithal to create an engine yourself, you should certainly have what it takes to structure your game such that swapping out the rendering back end is a relatively trivial operation.

Build your game, allow its specific needs to drive the feature set of the code you write, and write code with reusability and good architecture in mind. You will naturally end up with an "engine" after you finish a few projects like this, and you'll finish those projects faster because you're disallowing yourself from getting bogged down in framework-level feature creep.

# Answer
> 3 votes
It's very simple. Which is your primary goal: learning or time to market?

Avoid using a library if your primary goal is to learn from the experience of implementing the concepts that are solved by the library. Whenever I develop a game (part time), my goal is purely learning. I don't care how long it takes, thats why I'm doing it all from scratch! Now, you decide.

# Answer
> 0 votes
You should roll your own game engine when you **know** there is a *need* for it.

So for example, say you don't have the money to spend on Unity. Or, you'd rather spend it on new hardware instead. Or, there are performance issues with the free engines available to you, or you *need* to have more control at a low level.

If you love writing software for the sake of writing software, then you're going to love writing a game engine. A common **trapping** of beginning game programmers is to *get caught up writing an engine* as some kind perpetual project. I honestly believe that's how all these open source game engines came about -- game programmers who actually didn't

Then in that case, write your own engine.

---
Tags: ios, cocos2d
---


title: 2D Selective Gaussian Blur

text:
# Question
Title: 2D Selective Gaussian Blur
I am attempting to use Gaussian blur on a 2D platform game, selectively blurring specific types of platforms with different amounts. I am currently just messing around with simple test code, trying to get it to work correctly. What I need to eventually do is create three separate render targets, leave one normal, blur one slightly, and blur the last heavily, then recombine on the screen. Where I am now is I have successfully drawn into a new render target and performed the gaussian blur on it, but when I draw it back to the screen everything is purple aside from the platforms I drew to the target.

This is my .fx file:

```
#define RADIUS  7
#define KERNEL_SIZE (RADIUS * 2 + 1)

//-----------------------------------------------------------------------------
// Globals.
//-----------------------------------------------------------------------------

float weights[KERNEL_SIZE];
float2 offsets[KERNEL_SIZE];

//-----------------------------------------------------------------------------
// Textures.
//-----------------------------------------------------------------------------

texture colorMapTexture;

sampler2D colorMap = sampler_state
{
    Texture = <colorMapTexture>;
    MipFilter = Linear;
    MinFilter = Linear;
    MagFilter = Linear;
};

//-----------------------------------------------------------------------------
// Pixel Shaders.
//-----------------------------------------------------------------------------

float4 PS_GaussianBlur(float2 texCoord : TEXCOORD) : COLOR0
{
    float4 color = float4(0.0f, 0.0f, 0.0f, 0.0f);

    for (int i = 0; i < KERNEL_SIZE; ++i)
        color += tex2D(colorMap, texCoord + offsets[i]) * weights[i];

    return color;
}

//-----------------------------------------------------------------------------
// Techniques.
//-----------------------------------------------------------------------------

technique GaussianBlur
{
    pass
    {
        PixelShader = compile ps_2_0 PS_GaussianBlur();
    }
}

```

This is the code I'm using for the gaussian blur:

```
public Texture2D PerformGaussianBlur(Texture2D srcTexture,
                                             RenderTarget2D renderTarget1,
                                             RenderTarget2D renderTarget2,
                                             SpriteBatch spriteBatch)
        {
            if (effect == null)
                throw new InvalidOperationException("GaussianBlur.fx effect not loaded.");

            Texture2D outputTexture = null;
            Rectangle srcRect = new Rectangle(0, 0, srcTexture.Width, srcTexture.Height);
            Rectangle destRect1 = new Rectangle(0, 0, renderTarget1.Width, renderTarget1.Height);
            Rectangle destRect2 = new Rectangle(0, 0, renderTarget2.Width, renderTarget2.Height);

            // Perform horizontal Gaussian blur.

            game.GraphicsDevice.SetRenderTarget(renderTarget1);

            effect.CurrentTechnique = effect.Techniques["GaussianBlur"];
            effect.Parameters["weights"].SetValue(kernel);
            effect.Parameters["colorMapTexture"].SetValue(srcTexture);
            effect.Parameters["offsets"].SetValue(offsetsHoriz);

            spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
            spriteBatch.Draw(srcTexture, destRect1, Color.White);
            spriteBatch.End();

            // Perform vertical Gaussian blur.

            game.GraphicsDevice.SetRenderTarget(renderTarget2);
            outputTexture = (Texture2D)renderTarget1;

            effect.Parameters["colorMapTexture"].SetValue(outputTexture);
            effect.Parameters["offsets"].SetValue(offsetsVert);

            spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
            spriteBatch.Draw(outputTexture, destRect2, Color.White);
            spriteBatch.End();

            // Return the Gaussian blurred texture.

            game.GraphicsDevice.SetRenderTarget(null);
            outputTexture = (Texture2D)renderTarget2;

            return outputTexture;
        }

```

And this is the draw method affected:

```
    public void Draw(SpriteBatch spriteBatch)
    {
        device.SetRenderTarget(maxBlur);
        spriteBatch.Begin();
        foreach (Brick brick in blueBricks)
            brick.Draw(spriteBatch);
        spriteBatch.End();

        blue = gBlur.PerformGaussianBlur((Texture2D) maxBlur, helperTarget, maxBlur, spriteBatch);

        spriteBatch.Begin();
        device.SetRenderTarget(null);

        foreach (Brick brick in redBricks)
            brick.Draw(spriteBatch);

        foreach (Brick brick in greenBricks)
            brick.Draw(spriteBatch);

        spriteBatch.Draw(blue, new Rectangle(0, 0, blue.Width, blue.Height), Color.White);

        foreach (Brick brick in purpleBricks)
            brick.Draw(spriteBatch);

        spriteBatch.End();
    }

```

This is what it should look like(if it were blurred correctly)

This is what it currently looks like

I'm sorry about the massive brick of text and images, but I wanted to get my problem across clearly as I have been searching for an answer to this for quite a while now. As a side note, I have seen the bloom sample. Very well commented, but overly complicated since it deals in 3D; I was unable to take what I needed to learn form it. Thanks for any and all help.

# Answer
The purple background generally means that nothing is being rendered as that is the default back buffer color in XNA. I cannot verify this, but it looks like your order of drawing state swapping may be incorrect. Try setting the render target before beginning the spritebatch
> 3 votes

# Answer
The kernel is too big. Try reducing the size of the kernel, did you normalize the kernel coefficients? (So in that Paul Rideout example, he divides each weight by (1+4+6+4+1)=16). I know the kernel weights initially look to be 1,4,6,4,1, but they are actually 0.0625,0.25,0.375,0.25,0.0625
> 1 votes

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


# Question
Title: Data Structures for Logic Games / Deduction Rules / Sufficient Set of Clues?
I've been cogitating about developing a logic game similar to Einstein's Puzzle, which would have different sets of clues for every new game replay.

What data structures would you use to handle the different entities (pets, colors of houses, nationalities, etc.), deduction rules, etc. to guarantee that the clues you provide point to a unique solution?

I'm having a hard time thinking about how to get the deduction rules to play along with the possible clues; any insight would be appreciated.

# Answer
Wow. This actually seems like a situation where old-school AI semantic webs, like Richard Bartle thought were going to be important to the future of games when he wrote *Artificial Intelligence and Computer Games*, would be useful. You basically have a couple of data lists (database tables, whatever), the first of which specifies rules about how things can relate to each other, like:

```
a PERSON must LIVE IN a DOMICILE
a PERSON must OWN an ANIMAL
a PERSON must DRINK a BEVERAGE
a PERSON must SMOKE a CIGARETTE BRAND
a PERSON must BE OF a NATIONALITY
a DOMICILE must BE IN a POSITION
a DOMICILE must BE OF a COLOR

```

Then you have instances of the categories:

```
ANIMAL: dog snail zebra fox horse
BEVERAGE: milk tea OJ coffee water
CIGARETTE BRAND: Kools Parliaments Luckies OldGold Chesterfields
NATIONALITY: Englishman Spaniard Ukrainian Japanese Norwegian
POSITION: first second third fourth fifth
COLOR: red green yellow ivory blue

```

These data structures don't completely encapsulate the situation -- you need the uniqueness constraints, and some of the categories need meta-rules, like `POSITION` needs handling of the "to the right of", "to the left of", and "next to" concepts, for example -- but the structure of the problem seems to strongly suggest them.

Dunno if this will take you very far, but I hope it helps.
> 4 votes

# Answer
My recommendation is to look at the Python code for Constraint Satisfaction Problems (CSPs) provided with the AIMA project. They use a Dictionary (associative array/hash table) to keep track of valid constraints. Also, there are implementations of several algorithms used to solve CSPs, like min-conflicts and AC3.

The code includes a sample Zebra problem as an example, like the one you linked to.
> 4 votes

# Answer
This goes very deep actually. Strange that Wikipedia never mentions it.

What you are looking for are very hard proofs that can, probably, be reached with things like Fitch proofs. So we are trying to deduct things out of our given data. There are a lot of Fitch proof builders that do a lot of work for you. But some exercises are just not to proof.

I don't know if the user should do the calculations. If so, be aware of things like 3SAT, which are undoable problems for polynomial time.

As for the data structures you want to use, I think you want to have some kind of `Rule` class. The rule can be anything, depending on the type. There aren't a lot of rules in predicate logics, so this can be overcome by inheriting (if, iff, and, or, not...). These rules only have to be evaluated. And the only thing a rule can do, is return true or false. Because that is what you do with predicate logics. At university, I was recommended to read this book by John Kelly.

Going back to the classes: You should see these problems like you would see implementing normal calculations with math. What is a `+` operator? It contains two parameters, which can be a new equation by itself, or just a number. I think you have the same with Rules. They can have new Rules as a parameter, or just a boolean (so called predicate).

I hope this helps you a lot, especially the references. If you want to know more, or if I'm going into the wrong direction, please tell me.
> 1 votes

# Answer
I have no good answer, but looking for hints on the same kind of problem, I found this repository on github:

https://github.com/nateinaction/Zebra-Puzzle

It contains some logic for selecting clues and deciding how many clues you would need to make the puzzle solvable.
> 0 votes

# Answer
There's this on solving it.

Of course, I think it wouldn't be too difficult to work backwards; that is have a list like this:

* Fred Red Dog
* Steve Blue Cat
* Bill Purple Whale
* Eric Cyan Dolphin

Which could be easily generated, and then make up a set of rules from that.

As for storage, why not a set of each separate thing, so \[Fred, Steve, Bill, Eric\] and a set of the answer \[Fred, Red, Dog\]. Then have 'NAME does (not) ACTION OBJECT'.

When you get down to it, does a unique solution really matter? As long as your game can split them into the lists, and check 'set 1 does not contain Whale'.
> -1 votes

---
Tags: logic, data-structure, puzzle
---


# Question
Title: Keystone Correction using 3D-Points of Kinect
With XNA, I am displaying a simple rectangle which is projected onto the floor. The projector can be placed at an arbitrary position. Obviously, the projected rectangle gets distorted according to the projectors position and angle. A Kinect scans the floor looking for the four corners. Now my goal is to transform the original rectangle such that the projection is no longer distorted by basically pre-warping the rectangle.

My first approach was to do everything in 2D: First compute a perspective transformation (using OpenCV's `warpPerspective()`) from the scanned points to the internal rectangle's points und apply the inverse to the rectangle. This seemed to work but was too slow as it couldn't be rendered on the GPU.

The second approach was to do everything in 3D in order to use XNA's rendering features. First, I would display a plane, scan its corners with Kinect and map the received 3D-Points to the original plane. Theoretically, I could apply the inverse of the perspective transformation to the plane, as I did in the 2D-approach. However, since XNA works with a view and projection matrix, I can't just call a function such as `warpPerspective()` and get the desired result. I would need to compute the new parameters for the camera's view and projection matrix.

Question: Is it possible to compute these parameters and split them into two matrices (view and projection)? If not, is there another approach I could use?

# Answer
Since vector algebra is GPU friendly, normalizations and dot products can be used to find the four corners of the original plane as follow:

Given the projector point (P), the projected point (B), one arbitrary point on the plane that contains the distorted rectangle (Q), and the normal vector to that plane (n), the point of intersection (A) of the line from P to B, and the plane is given by

```
s = -dot_product(n, P - Q) / dot_product(n, normalized(B - P))
A = P + s * normalized(B-P)

```

Source http://geomalgorithms.com/a05-\_intersect-1.html section Line-Plane Intersection
> 1 votes

---
Tags: xna, 2d, 3d, projection, kinect
---


# Question
Title: Flip sprite vertically AND horizontally?
In `Microsoft.Xna.Framework.Graphics.SpriteEffects` there is the possibility to flip a texture horizontally or vertically before rendering. But can one do both at the same time?

When I use: `spriteEffect = SpriteEffects.FlipHorizontally | SpriteEffects.FlipVertically;` with `spriteEffect` being a parameter of the particle. The method `spriteBatch.Draw(spriteSheet,
 currentPositionForDraw,
 sourceRectangle,
 currentColorMultiplied,
 currentRotation,
 currentOriginForDraw,
 Temp.delta,
 spriteEffect,
 0);` does not draw the particle flipped on both axis.

# Answer
Yes. If you look at the definition of that enum you'll see it has \[FlagsAttribute\] which means you can combine the enum values with the | operator.
> 6 votes

# Answer
If you don't care about rotation, you can simply set the origin of the sprite to its center and rotate it 180 degrees (`Math.PI`). This is the same as flipping horizontally and vertically.

If you *do* care about rotation, and the sprite is flipped both ways, you can just add `Math.PI` to the angle and you should be done (eg. 45 degrees + 180 degrees rotation looks the same as 45-degrees flipped on both axes).
> 7 votes

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


title: Loading files while running game

text:
# Question
Title: Loading files while running game
I am curious as to what technique(s) are used to load files in while a game is running. For example, Minecraft will load chunks as you get within a certain range of them. How is this achieved without producing lag? Is multithreading involved?

# Answer
Yes, this can be solved with multithreading. Either explicitly by creating a new thread which reads and interprets a file, or implicitly by using an asynchronous file access API which calls a callback function when a file finished loading.

The biggest problem with loading assets on demand is what to do when an asset is needed immediately, but it hasn't loaded yet. You can either pause the game until the asset is loaded (which is annoying), or replace it with a temporary placeholder (which can break immersion).
> 3 votes

---
Tags: c++, loading, file
---


# Question
Title: Where should I place input/output console for server?
I'm developing a simple 2d online game and now I'm designing my server. The server will be run on linux vps and I need a way to communicate with it (for example to close it, and as it will be run on vps, simply closing terminal won't work). So I think there are 2 options:

1) Write 2 apllications - server which doesn't say anything and doesn't accept console input and the second application is console which sends commands to server (like exit, get online players etc).

2) Have 2 threads on the server appplication - one is the real server, the second thread will be used for cin and cout. However I'm not sure if this will work on vps...

Or maybe there is better aproach? What is the usual way of doing this?

# Answer
> 0 votes
You can definitely use stdin/ stdout on a Linux or Windows-based server process. It is possible to multiplex it (with sockets, for instance), or handle it in a separate thread from the rest of your server (only useful if you have sufficient locking, or maybe do something simple like queue the commands for your server).

In Linux it is common practice to run such a server under a persistent-terminal program such as "screen" or "tmux", then you can log in later (securely, e.g. via ssh) and look at the output, and supply input.

Likewise, if it's a Windows server, you can run it in a remote desktop session and then reconnect later.

Do the simplest thing which could possibly work; you'll have bigger problems.

# Answer
> 1 votes
If you're running your server from a remote host, you'll absolutely need to use the first option. Otherwise, I would go with the second option for simplicity's sake.

Keep in mind that if you use the first option, it's possible that hackers will be able to shut down or modify your server. At the same time, though, you also get the added benefit of allowing administrators other than you to perform these operations.

---
Tags: server, online, console
---


title: Designing for visually impaired gamers

text:
# Question
Title: Designing for visually impaired gamers
> Globally the number of people of all ages visually impaired is estimated to be 285 million, of whom 39 million are blind.
>
> World Health Organisation, 2010.

(That's 4.2% and 0.6% of the world population.)

Most videogames put a strong emphasis on visuals in their content delivery. Visually impaired gamers are largely left out.

How do I design a game to be accessible to visually impaired gamers?

# Answer
Take a look at Game Accessibility Guidelines, lots of advice on there. Did you have something specific in mind that you wanted to design?

Caius is right in saying that there are mechanics that can't easily be adapted for blind gamers. Most can easily be improved for people with other varying degrees of visual impairment though - avoiding tiny low contrast text for example.
> 9 votes

# Answer
There are some genres that, I am told, work well for totally blind players.

One option is a text only interface, such as multi-user dungeons, and zork-style interactive fiction both of which are popular with sighted people like me. A user can hook them up to a braille display or a screen reader, or if partially sighted, adjust the contrast, text size, font and color.

A Google search turns up a small but creative community in audio games:
> 3 votes

# Answer
The advent of iOS has meant an explosion in blind-accessible games. Some that are designed specifically with blind gamers in mind, such as Papa Sangre and Nightjar, and many many others where the simple visual element makes them ideally suited to someone running their finger over the screen to explore the interface, games like Hanging with Friends, Wordundrum and iAssociate 2.

That's how VoiceOver, the iOS screenreader, works - you drag your finger around the screen and it speaks out whatever is underneath your finger at the time, so it's literally just a case of making sure everything is labelled correctly.

Interesting stuff eh?

http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/iPhoneAccessibility/Accessibility\_on\_iPhone/Accessibility\_on\_iPhone.html
> 3 votes

---
Tags: game-design, accessibility
---


# Question
Title: rotate sphere horizontally around another sphere
I currently have an earth and a moon. What I'm trying to achieve is to have the moon physically rotate **around the earth horizontally along the equator** along a circular path.

```
    moonAngle = (moonAngle + 0.5f) % 360f;
    xPath = (float) Math.sin(Math.toRadians(moonAngle)) * distance;
    yPath = (float) Math.cos(Math.toRadians(moonAngle)) * distance;

    gl.glTranslatef(xPath, yPath, -30f);

```

The above works fine, except the moon is rotating around the earth **vertically around the Prime Meridian** like a wall clock. How do I adjust the angle of rotation? I've tried modifying the `glTranslatef`, but with no success.

# Answer
The `Y` offset you are computing should actually be applied to the `Z` axis:

```
gl.glTranslatef(xPath, 0f, yPath - 30f);

```
> 2 votes

---
Tags: opengl, rotation, jogl
---


title: HLSL shader optimization

text:
# Question
Title: HLSL shader optimization
The following HLSL shader (without preprocessing) results in 65 arithmetic operations (see below). Can the same effect achieved with \<=64 operations?

```
// Center of "light"
float x;
float y;

// Size of "light"
float viewsizeQ;
float fadesizeQ;

// Rotational shift
float angleShift;

// Resolution
float screenResolutionWidth;
float screenResolutionHeight;
float screenZoom;

// Texture sampler
sampler TextureSampler : register(s0);

float4 main(float2 texCoord : TEXCOORD0) : COLOR0
{
    // Look up the texture color.
    float4 color = tex2D(TextureSampler, texCoord);

    // Calculate distance
    float dx = (x-texCoord.x) * screenResolutionWidth;
    float dy = (y-texCoord.y) * screenResolutionHeight;

    // Get angle from center
    // Added into next line to save that variable
    //float angleFactor = sin((atan2(dx, dy) + angleShift) * 12) * 13000 * screenZoom * screenZoom;

    float distQ = dx*dx + dy*dy - /*angleFactor*/ sin((atan2(dx, dy) + angleShift) * 12) * 13000 * screenZoom * screenZoom;

    // Get greyscale
    float greyscale = dot(color.rgb, float3(0.3, 0.59, 0.11));

    // Within fadeSize
    if (distQ < fadesizeQ)
    {
       // Within viewSize
       if (distQ < viewsizeQ)
       {
          // Make blue-greyscale
          color.r = 0.3f * greyscale;
          color.g = 0.5f * greyscale;
          color.b = 1.0f * greyscale;
       }
       // Outside viewSize but still in fadeSize
       else
       {
          // Make
          float factor = 1.0f - ((distQ  - viewsizeQ) / (fadesizeQ - viewsizeQ));
          color.r = factor * 0.3f * greyscale + (1-factor) * 0.2f * greyscale;
          color.g = factor * 0.5f * greyscale + (1-factor) * 0.25f * greyscale;
          color.b = factor * 1.0f * greyscale + (1-factor) * 0.2f * greyscale;
       }
    }
    // Outside fadeSize (just show grey terrain)
    else
    {
        color.rb = 0.2f * greyscale;
        color.g = 0.25f * greyscale;
    }

    return color;
}

technique Thermal
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 main();
    }
}

```

The following output is created by the Microsoft Shader Compiler:

```
C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Utilities\bin\x86>fxc 07_EffectThermalVisionLevel.fx /T ps_2_a /Zi

Microsoft (R) Direct3D Shader Compiler 9.29.952.3111
Copyright (C) Microsoft Corporation 2002-2009. All rights reserved.

//
// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
//
//   fxc 07_EffectThermalVisionLevel.fx /T ps_2_a /Zi
//
//
// Parameters:
//
//   sampler2D TextureSampler;
//   float angleShift;
//   float fadesizeQ;
//   float screenResolutionHeight;
//   float screenResolutionWidth;
//   float screenZoom;
//   float viewsizeQ;
//   float x;
//   float y;
//
//
// Registers:
//
//   Name                   Reg   Size
//   ---------------------- ----- ----
//   x                      c0       1
//   y                      c1       1
//   viewsizeQ              c2       1
//   fadesizeQ              c3       1
//   angleShift             c4       1
//   screenResolutionWidth  c5       1
//   screenResolutionHeight c6       1
//   screenZoom             c7       1
//   TextureSampler         s0       1
//

ps_2_x
def c8, 0.0208350997, -0.0851330012, 0.180141002, -0.330299497
def c9, 0.999866009, 0, 1, 3.14159274
def c10, -2, 1.57079637, 1.9098593, 0.5
def c11, 6.28318548, -3.14159274, 13000, 0
def c12, 0.300000012, 0.589999974, 0.109999999, 0.5
def c13, 0.200000003, 0.25, 0, 0
def c14, -1.55009923e-006, -2.17013894e-005, 0.00260416674, 0.00026041668
def c15, -0.020833334, -0.125, 1, 0.5
dcl t0.xy  // texCoord<0,1>
dcl_2d s0

#line 26 "C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Utilities\bin\x86\07_EffectThermalVisionLevel.fx"
add r0.w, -t0.x, c0.x
mul r0.x, r0.w, c5.x  // ::dx<0>
add r0.z, -t0.y, c1.x
mul r0.z, r0.z, c6.x  // ::dy<0>

#line 33
abs r0.yw, r0.xxzz
max r1.w, r0.y, r0.w
rcp r1.x, r1.w
min r1.y, r0.w, r0.y
add r0.y, -r0.y, r0.w
cmp r0.y, r0.y, c9.y, c9.z
mul r0.w, r1.x, r1.y
mul r1.x, r0.w, r0.w
mad r1.y, r1.x, c8.x, c8.y
mad r1.y, r1.x, r1.y, c8.z
mad r1.y, r1.x, r1.y, c8.w
mad r1.x, r1.x, r1.y, c9.x
mul r0.w, r0.w, r1.x
mad r1.x, r0.w, c10.x, c10.y
mad r0.y, r1.x, r0.y, r0.w
cmp r0.w, r0.z, -c9.y, -c9.w
add r0.y, r0.w, r0.y
add r0.w, r0.y, r0.y
max r1.x, r0.x, r0.z
cmp r1.x, r1.x, c9.z, c9.y
min r1.y, r0.z, r0.x
mul r0.z, r0.z, r0.z
mad r0.x, r0.x, r0.x, r0.z
cmp r0.z, r1.y, c9.y, r1.x
mad r0.y, r0.z, -r0.w, r0.y
add r0.y, r0.y, c4.x
mad r0.y, r0.y, c10.z, c10.w
frc r0.y, r0.y
mad r0.y, r0.y, c11.x, c11.y
sincos r1.y, r0.y, c14, c15
mul r0.y, c7.x, c7.x
mul r0.y, r1.y, r0.y
mad r0.x, r0.y, -c11.z, r0.x  // ::distQ<0>

#line 39
add r0.y, r0.x, -c3.x

#line 42
add r0.x, r0.x, -c2.x

#line 53
mov r1.x, c3.x  // ::fadesizeQ<0>
add r0.z, r1.x, -c2.x
rcp r0.z, r0.z
mad r0.z, r0.x, -r0.z, c9.z  // ::factor<0>

#line 23
texld r1, t0, s0  // ::color<0,1,2,3>

#line 36
dp3 r2.z, r1, c12  // ::greyscale<0>

#line 54
mul r0.w, r0.z, r2.z
add r2.w, -r0.z, c9.z
mul r2.w, r2.z, r2.w
mul r3.xy, r2.w, c13
mad r4.xy, r0.w, c12.xwzw, r3  // ::color<0,1>
mad r4.z, r0.z, r2.z, r3.x  // ::color<2>

#line 42
mul r2.xy, r2.z, c12.xwzw
cmp r0.xzw, r0.x, r4.xyyz, r2.xyyz  // ::color<0,1,2>

#line 63
mul r2.xyz, r2.z, c13.xyxw  // ::color<0,1,0>

#line 39
cmp r1.xyz, r0.y, r2, r0.xzww  // ::color<0,1,2>
mov oC0, r1  // ::main<0,1,2,3>

```

# Answer
> 2 votes
You need to think of the built-in HLSL functions that let you perform tests (`min`, `max`, `saturate`…) or interpolations (`lerp`, `smoothstep`…). Many times they map to a single assembly instruction on the hardware.

Also, as Adam mentioned in his answer, it’s best to try to parallelise operations. Adding two `float` has exactly the same cost as adding two `float4`.

Using all these ideas, the following code uses a lot fewer instructions. I took the liberty of renaming `greyscale` to `luminance`:

```
float4 main(float2 texCoord : TEXCOORD0) : COLOR0
{
    // Look up the texture color.
    float4 color = tex2D(TextureSampler, texCoord);

    // Calculate distance
    float2 delta = (float2(x, y) - texCoord.xy)
                 * float2(screenResolutionWidth, screenResolutionHeight);

    // Get angle from center
    float distQ = dot(delta, delta)
       - /*angleFactor*/ sin((atan2(delta.x, delta.y) + angleShift) * 12)
                          * 13000 * screenZoom * screenZoom;

    float luminance = dot(color.rgb, float3(0.3, 0.59, 0.11));
    float3 grey = float3(0.3, 0.5, 1.0);
    float3 blue = float3(0.2, 0.25, 0.2);
    float factor = saturate((distQ  - viewsizeQ) / (fadesizeQ - viewsizeQ));

    color.rgb = luminance * lerp(grey, blue, factor);
    return color;
}

```

# Answer
> 1 votes
My first suggestion would be to combine both the x and y variables and the screen resolution into a float2 which then lets you do the distance calculation in one line. That should get rid of a few instructions.

I'd also suggest passing the square of the screenZoom as a constant if you only use it squared in the calculations.

```
float2 lightPosition;
float2 screenResolution;

    // Calculate distance
    float2 distance = (lightPosition-texCoord) * screenResolution;

```

---
Tags: xna, c#, xna-4.0, hlsl, fragment-shader
---


# Question
Title: What size window should i use for making an Xbox 360 game in XNA
I have a basic understanding of XNA 4.0 and i want to create an xbox game. What size window should i use? should i use the 16:9 aspect ratio then put it in full screen?

# Answer
> 3 votes
Best practice is to use the default setting, 1280x720. This allows the console to upconvert to 1080i at no cost to you (dedicated hardware for it), or letterbox down to SD resolutions, again at not cost to you. Doing anything else requires a lot of code. It is feasible to accomplish, but normally has little benefit and is not easy.

Also, for publishing on XboxLive, if you try to implement a custom resolution detector/selector, and it doesn't work, that is cause for rejection during peer review.

Edit: unfortunately, the official best practices article seems to be a broken link over at xbox.create.msdn.com, but the evil checklist for peer-review also recommends 1280x720.

---
Tags: xna-4.0
---


# Question
Title: How do I export a Java project on Eclipse as an executable?
I made a Java project with images, external JARs, and natives(the JARs and natives are for LWJGL and Slick). How can I export this as an executable? I already tried JarSplice and WinRun4J, but when I run the executable, nothing happens. Why?

EDIT: There are also sound files and TrueType fonts.

# Answer
I like to use Launch4j to generate my Java ".exe" files for Windows. You can let the executable auto-download the necessary Java VM if necessary, and, for debug purposes, you can start your executable in console, so if an error happens, you will be able to see what is causing it.

Just remember to ship the extra files with your executable (dlls, images, others)... To create a Windows installer, I recommend NSIS.
> 5 votes

---
Tags: java
---


# Question
Title: Implementing AI to hide behind obstacles
I am developing an AI simulation of predator and prey. I would like to simulate the AI hiding behind obstacles, if it is being chased. But I am still trying to figure out the best way to implement this.

I was thinking along the lines of checking on which side of the obstacle the predator is on and trying to go on the opposite side. Maybe using the A\* path finding algorithm to ensure that it gets there using the shortest path.

Now the main reason I am writing is in case somebody is able to point me in the right direction of implementing this (maybe somebody has done this before) or have any other good ideas how to implement it. I have never done anything like this before in terms of programming AI or making any game.

All the obstacles are either horizontal or vertical squares/rectangles.

**Additional Info:** The map is based on x,y positions with each agent moving at a set velocity.So the map is not entirely tile based, also for that reason I am unsure if A\* would actually work in this situation for me.

Here is an image of the situation:

**Please also note that the red circle is the predator while the green circle is the prey being chased by the predator.**

# Answer
> 3 votes
You can add this kind of behavior to any path-finding algorithm simply by adjusting the heuristic function. A typical heuristic for path-finding is just based on distance to the goal, however, you can factor in an estimate of how dangerous a given spot is:

```
// Typical heuristic function, lower values are better
float Heuristic(Vector position, Vector goal)
{
    return (goal - position).Length();
}

// New heuristic function
float Heuristic(Vector position, Vector goal)
{
    float value = (goal - position).Length();

    if(TestLineOfSight(enemy, position))
    {
        value += enemy.Level * 100.0f; // Higher-level enemies are more dangerous
    }

    // You can also add factors like environmental hazards, etc.

    return value;
}

```

This new heuristic will make your actors try to path-find around areas they perceive as dangerous. This technique is really great because it works with any heuristic-based path-finding algorithm.

**Note:** Path-finding algorithms like A\* may need a little tweaking to allow the algorithm to back-track in case it comes across an area deemed too dangerous to cross.

# Answer
> 1 votes
You can make the Prey use an algotithm to determine that, at a given moment, the Predator will not directly "see" it if it hides behind an obstacle.

This is how it could be done:

1. Prey finds an obstacle.
2. In order to determine if the obstacle can be used for hiding, the Prey makes a list of possible spots it can stand around the found obstacle.
3. For each of these spots, the Prey traces a line from the Predator to itself. Once it finds a line that crosses that obstacle, it means the obstacle is standing in the way between them. That's when the Prey found a hiding spot.

Then, you make the Prey move to that spot.

Edit: implying you're using a tile-based map.

# Answer
> 0 votes
You can treat this as a max/min tree. The goal would be to minimize the "visibility" of the predator. You can compute values as something like:

* Predator's direct line/range of sight: 100
* Open areas, but not in predator's sight: 50
* Not visible by predator's sight: 0

In this case, it's a simpler problem of "pick the next best move." That would mean, the next move that takes you towards getting into a zero-visibility area.

# Answer
> 0 votes
For the nearest obstacle that's both...

1. Long or wide enough to hide behind.
2. Further from the predator than it is from you.

See if you can get to the opposite side of the obstacle from the predator. Just:

```
xPosToGoTowards = (2 * xPos_Obstacle) - xPos_Predator
yPosToGoTowards = (2 * yPos_Obstacle) - yPos_Predator

```

If you can't get there without bumping into things, check the *next* closest obstacle. The first obstacle might pass the test later after a bit more running, but it will also keep the AI more interesting if it doesn't always hide behind the closest obstacle.

There are far more ingenious solutions out there, but that's a *bad* thing if you don't need it. Simple is good.

---
Tags: java, ai, movement
---


title: A simple example of movement prediction

text:
# Question
Title: A simple example of movement prediction
I've seen lots of examples of theory about the reason for client-side prediction, but I'm having a hard time converting it into code. I was wondering if someone knows of some specific examples that share some of the code, or can share their knowledge to shed some light into my situation.

---

I'm trying to run some tests to get a the movement going (smoothly) between multiple clients. I'm using mouse input to initiate movement.

I'm using AS3 and C# on a local Player.IO server. Right now I'm trying to get the Client side working, as I'm only forwarding position info with the client.

I have 2 timers, one is an onEnterFrame and the other is a 100ms Timer, and one on mouseClick listener.

* When I click anywhere with a mouse, I update my player class to give it a destination point
* On every enterFrame Event for the player, it moves towards the destination point
* At every 100ms it sends a message to the server with the position of where it should be in a 100ms.
* The distance traveled is calculated by taking the distance (in Pixels) that the player can travel in one second, and dividing it by the framerate for the onEnterFrame handler, and by the update frequency (1/0.100s) for the server update.
* For the other Players, the location is interpolated and animated on every frame based on the new location.

Is this the right way of doing it?

# Answer
Does the server know the destination point? If not, it might be a problem if you get lost or late messages, which is always a risk with networking.

Even if, on the second lost message in a row, you add the player's velocity again to keep moving them by the same distance as they moved in the previous 100ms, it will overshoot the player if messages are lost after player reaches the destination point. What you could do is either transmit the destination point to the server as well so it knows when to stop.

Also make sure things don't break badly if the client's frame-rate stutters, or a later message gets to the server before an earlier one, or arrives after you thought you'd stopped listening for it. A player position going astray for a few frames probably isn't a big deal, but make sure nothing can get permanently corrupted or out of synch.
> 1 votes

# Answer
Yes, I think that would be the right way. If that doesn't work out, you should try using the x/y velocity to predict where he'll be, based on how often you run an update, and how fast he's going, for instance, if you run an update every 50ms, and the player is going at 1 pixel x per update, and 1 pixel y per update, than you predict the player to be two steps ahead, assuming that his velocity is consistant.
> 0 votes

---
Tags: networking, multiplayer, client-server, client
---


# Question
Title: Curious Transparent Holes Render Artifact
So I'm trying to implement "smooth" terrain in my block engine by giving each surface block a heightmap.

Basically, what I do to generate these "heightmaps" for each block is I generate the heights at intervals of 0.25 along the edge of the block. Then, to build the block's vertices, I loop through the heights and create triangles from height to height and put rectangles under the triangles to create something like this:

For example, to build the X positive side of a block, I do:

```
                    Vector2[] uv = BlockUtil.UVMappings[(byte)side]; // uv[0] = top left

                    float height;
                    float nextHeight;
                    float min;

                    float tex_len = 1f / EngineGlobals.TEXTURE_ATLAS_SIDE;

                    for (int i = 0; i < 4; i++)
                    {
                        height = (float)b.Heights[4, i] / 255f;

                        nextHeight = (float)b.Heights[4, i + 1] / 255f;

                        min = Math.Min(height, nextHeight);

                        //create the triangles at the top
                        if (nextHeight > height)
                        {
                            int offset = ch.vertexMap.Count;

                            AddVertex(ch, 0, 0, uv[0] + new Vector2(tex_len * (i / 4f), (1-height)*tex_len), blockPos, new Vector3(1f, height, i / 4f), tr, isliquid);
                            AddVertex(ch, 0, 0, uv[0] + new Vector2(tex_len * ((i + 1) / 4f), 0), blockPos, new Vector3(1f, height, (i + 1) / 4f), tr, isliquid);
                            AddVertex(ch, 0, 0, uv[0] + new Vector2(tex_len * ((i + 1) / 4f), 0), blockPos, new Vector3(1f, nextHeight, (i + 1) / 4f), tr, isliquid);

                            AddTriIndices(offset, 0, 1, 2);
                        }
                        else if (nextHeight < height)
                        {
                            int offset = ch.vertexMap.Count;

                            AddVertex(ch, 0, 0, uv[0] + new Vector2(tex_len * (i / 4f), (1-height)*tex_len), blockPos, new Vector3(1f, height, i / 4f), tr, isliquid);
                            AddVertex(ch, 0, 0, uv[0] + new Vector2(tex_len * (i / 4f), (1-nextHeight)*tex_len), blockPos, new Vector3(1f, nextHeight, i / 4f), tr, isliquid);
                            AddVertex(ch, 0, 0, uv[0] + new Vector2(tex_len * ((i + 1) / 4f), (1 - nextHeight) * tex_len), blockPos, new Vector3(1f, nextHeight, (i + 1) / 4f), tr, isliquid);

                            AddTriIndices(offset, 0, 1, 2);
                        }
                        // else: heights are equal; ignore

                        // create the base rectangle
                        AddVertex(ch, 0, 0, uv[0] + new Vector2(tex_len * (float)i / 4f + tex_len / 4f, (1 - min) * tex_len), blockPos, new Vector3(1, min, (float)(i + 1) / 4f), tr, isliquid);
                        AddVertex(ch, 0, 1, uv[0] + new Vector2(tex_len * (float)i/4f, (1 - min) * tex_len), blockPos, new Vector3(1, min, (float)i / 4f), tr, isliquid);
                        AddVertex(ch, 0, 2, uv[0] + new Vector2(tex_len * (float)i / 4f + tex_len / 4f, tex_len), blockPos, new Vector3(1, 0, (float)(i + 1) / 4f), tr, isliquid);
                        AddVertex(ch, 0, 3, uv[0] + new Vector2(tex_len * (float)i / 4f, tex_len), blockPos, new Vector3(1, 0, (float)i / 4f), tr, isliquid);

                        AddIndices(ch, 0, 1, 2, 2, 1, 3, isliquid);
                    }

```

I'm not sure if this is a floating point precision error, but when I render it, I get these curious holes on the borders of the base rectangles (I know they're holes because their colors match the color behind them)

What really throws me off is that rather than a whole line, it's just seemingly random dots.

A wireframe view of the world did not reveal any discrepancies. (all it did was make the game lag)

A quick little hack that I did was to extend the (i+1)/4 in the code to (i+1.01f)/4, but I'd rather get a concrete solution than something like that.

Perhaps it's something in my shader? My texture sampler is:

```
Texture TextureAtlas;
sampler TextureSampler = sampler_state
{
        texture = <TextureAtlas>;
    magfilter = POINT;
    minfilter = POINT;
    mipfilter = POINT;
    AddressU = WRAP;
    AddressV = WRAP;
};

```

Thanks in advance!

# Answer
> 15 votes
From your diagram, it looks like the geometry you're constructing contains T-junctions - places where a vertex of one triangle is supposed to lie exactly on another triangle's edge (resulting in one edge meeting another in a "T" shape). Due to the limitations of finite-precision arithmetic, the vertex usually cannot be guaranteed to meet the edge perfectly and you will find microscopic cracks between them, which often show up as single-pixel glitches because an individual pixel may happen to land in the crack while its neighbors don't.

To fix it, you have to build your geometry in such a way that there are no T-junctions, by splitting each edge where a vertex is supposed to meet it. This diagram shows an example:

EDIT: The above applies to T-junctions in general. For your specific case, as Ilmari Karonen pointed out in the comments, you can build the geometry even better like this:

which also avoids T-junctions and has fewer triangles overall.

---
Tags: xna, directx, shaders, voxels, debugging
---


# Question
Title: Any drawback to using rectangular textures over square textures in OpenGL?
I'm thinking about texture atlas generation where I'd have to choose the dimensions of my atlas, constrained both by my sprites and by the maximum texture size of the current platform.

Given that, is there any drawback to using a rectangular texture over a square texture, assuming the dimensions are still a power of two? For example, is there a difference between using a 64x256 texture and using a 128x128 texture?

# Answer
Short answer: no, there's no drawback.

In early 3d hardware there used to be some aspect ratio limitations, where you could do 32x256 or 256x32 textures, but not, for example, 256x4. I have no idea why this limitation existed (probably to simplify interpolators or some such), but current 3d hardware has no such limitation.

Do note that small levels of mipmaps may act slightly differently in non-square textures (as an example, 64x8 - 32x4 - 16x2 - 8x1 - 4x1 - 2x1 - 1x1, I believe).
> 4 votes

---
Tags: opengl, textures
---


# Question
Title: Draw user interface in OpenGL using web technologies
I am developing a desktop game in C++ and OpenGL. Frameworks I use are GLM and SFML. Since today I used the console window for debug messages. But I want to get rid of that and display debug information right into the render window.

Since I also want to implement a generic way to realize user interface, I decided to use web technologies for that. Note that the user interface will be only a two dimensional overlay on the rendered three dimensional scene. I consider using the webkit browser engine but that might be overkill since I do not need page loading and networking but only HTML and CSS rendering (and maybe JS execution). Because the user interface and debug messages will change every few frames, this is performance related.

How to render fullscreen webpages (with a transparent background) over my OpenGL scene? I would like a cross-platform solution.

# Answer
> 2 votes
Apart from implementing it yourself, there's http://awesomium.com/, which is basically webkit wrapped in a way that makes it simpler to plug into applications.

http://librocket.com/ is apparently a completely separate html/css engine for games, but apparently hasn't been updated since 2011, so I don't know if it's alive.

---
Tags: c++, opengl, html, css
---


# Question
Title: High volume sprite management in entity component system
I'm working on an entity-component-system based 2.5d game. That is, entities are groups of components that are processed by systems. I am having a hard time seeing how a sprite rendering system, that targets entities with a "RenderableSprites" component, can effectively manage components when processing so that only sprites that are on screen are iterated and subsequently drawn. I can see various solutions with LINQ etc. but they all require iteration through the collection of components whether explicit or not.

What is the common practice to deal with this problem, even if not in the paradigm of entity component systems?

To solve this problem with my tile based "floor" entity, it was best to group the floor tiles into one entity whereas before they were separate. This allows indexing of tiles by position in a tilemap so that every update step (to be later limited to updates where camera movement is detected), tiles are methodically **selected** rather than **filtered via iteration** and propagated to the "RenderableSprites" component, hence tiles that are not on screen are not processed in the draw step.

I am now adding scenery entities, but it doesn't scale particularly well when each tree is a seperate entity. Any suggestions as to whether scenery should be grouped into one entity? This seems to defeat the point of an entity component system and my spidey senses tell me this will lead to difficulty calculating collision etc.

Any feedback much appreciated! I am working in XNA but I don't consider this a very language specific question.

To anyone interested: I'm in the processing of working around this; I am constructing an entity manager storing entities by ID, something I should have done earlier. This will allow me to maintain some spatial indexes against entity IDs that the sprite renderer can reference before selecting which entities to process from the manager. This is as opposed to each System holding concrete references to its target components. I will maybe post some code when I'm done.

# Answer
> 3 votes
1. Keep list of compatible components in each system. This way you don't have to iterate over every entity. Your entity manager can take each new entity, and dispatch its components to the correct systems.
2. IMO tiles shouldn't be entities. It's just too memory expensive. Also, as you noticed, tilemap needs special treatment in rendering (also physics), where you want to select some area of tiles, instead of iterating over each tile.

---
Tags: xna, c#, sprites, entity-system, 2.5d
---


title: Blur shader without render textures?

text:
# Question
Title: Blur shader without render textures?
Is it possible to append a blur shader to a standard (diffuse) shader ? I am looking for a way to do this as Unity indie doesn't allow render textures.

# Answer
In theory, you could use Shader Replacement to re-render your whole scene using shaders that offset the positions of everything slightly, and output with e.g. 25% alpha.

So you'd render the scene normally, and then:

```
Clear depth buffer
Set shader replacement to offset everything 1px left and 25% alpha
Render
Clear depth buffer
Set shader replacement to offset everything 1px right and 25% alpha
Render
Clear depth buffer
Set shader replacement to offset everything 1px up and 25% alpha
Render
Clear depth buffer
Set shader replacement to offset everything 1px down and 25% alpha
Render

```

Or something along those lines, anyway.
> 2 votes

---
Tags: unity, shaders, post-processing
---


# Question
Title: How do I get buffers from another class for CreateBuffer
I believe this is not strictly specific to DirectX but just to pure c++ language problem.

I have a class (simplified):

```
class A {
public:
    ID3D11Buffer* getVBuffer() const {
        return m_vbuffer;
    }

    // I will make this public for this example
    ID3D11Buffer* m_vbuffer;
};

```

and then in some other place I am creating vertex buffer:

```
device->CreateBuffer( ..., &instanceOfA->m_vbuffer );

```

it works ok, but why with the getter method doesn't?

```
ID3D11Buffer* _vertexBuffer = instanceOfA->getVBuffer();
device->CreateBuffer( ..., &_vertexBuffer  );

```

it crashes at Map function with access violation, but I'd like to have getter method used.

// EDIT

when I wrote like this:

```
device->CreateBuffer( ..., &instanceOfA->getVBuffer()  );

```

the compiler (VS2012) told me:

```
error C2102: '&' requires l-value

```

Is it then even possible to use getters in this situation?

# Answer
It's a pointer misunderstanding.

Consider this, even more simplified example:

```
ID3D11Buffer *original_buffer = NULL;
ID3D11Buffer *returned_buffer = original_buffer;

```

Okay, so you have two pointers that both point to the same location. This is what happens when you call the getter. The only thing they have in common is that they point to the same address.

```
device->CreateBuffer(&returned_buffer);

```

Now, your "returned\_buffer" points to the newly created buffer. The "original\_buffer" still points to its initial value NULL.

```
device->MapBuffer(original_buffer);

```

... and you try to map NULL. Boom!
> 2 votes

---
Tags: c++, directx11
---


title: SDL deleting an image from the screen?

text:
# Question
Title: SDL deleting an image from the screen?
Well, I'm sort of a beginner to SDL, and I was wondering how one would go about deleting an image from the screen and replacing it with another? I attempted to do this, but it didn't seem to change it, how would someone with more experience than me go about doing it?

# Answer
> 1 votes
You need to flip the buffer surface to the screen to make it update. You need `SDL_Flip` function.

Take a look at this tutorial: Lazy Foo' SDL Tutorial

---
Tags: graphics, sdl
---


title: Torque2D default t2dTileMap object

text:
# Question
Title: Torque2D default t2dTileMap object
When I start a blank project I have noticed that I get one `t2dSceneGraph` and one `t2dTileMap` (under the project tab). I selected the `t2dTileMap` and gave it a name '*tilemap*'.

In my `game.cs` function `startGame` I added

```
%LayerCount = tilemap.getTileLayerCount();

```

...but when I execute the project and inspect the variable `%LayerCount` in Torsion I first of all get an error:

```
Unable to find object: 'tilemap' attempting to call function 'getTileLayerCount'

```

How do I access the default `t2dTileMap`?

# Answer
> 0 votes
Never mind here is the answer if somone else would like to know...

```
%tileMap = $LastLoadedScene.getGlobalTileMap();
%layerCount = %tilemap.getTileLayerCount();

```

---
Tags: scripting, torque
---


title: XNA - moving the 3rd person camera

text:
# Question
Title: XNA - moving the 3rd person camera
I'm having following problem: Can't set my camera to follow object from behind and rotate when I use left/right arrow. I've tried different tutorial and examples but it still doesn't work for me. Don't know where I'm wrong

this is the code for handle input - so far I've removed the rotation option so the code can compile

```
 if (currentKeyboardState.IsKeyDown(Keys.Up))
        {
            zTranslationPosition -=5;
            //translatePosition.Z=-  1;
            animationCat.StartClip(animationCat.walk_R);
            animationCat.Update(gameTime.TotalGameTime, true, Matrix.Identity);
        }
        if (currentKeyboardState.IsKeyDown(Keys.Down))
        {
            zTranslationPosition += 5;
            //translatePosition.Z =+  1;
            animationCat.StartClip(animationCat.walk_R);
            animationCat.Update(gameTime.TotalGameTime, true, Matrix.Identity);
        }
        if (currentKeyboardState.IsKeyDown(Keys.Left))
        {
            xTranslationPosition -=5;
           // turn += 1;
            animationCat.StartClip(animationCat.walk_R);
            animationCat.Update(gameTime.TotalGameTime, true, Matrix.Identity);
        }
        if (currentKeyboardState.IsKeyDown(Keys.Right))
        {
           // turn -= 1;
            xTranslationPosition +=5;
            animationCat.StartClip(animationCat.walk_R);
            animationCat.Update(gameTime.TotalGameTime, true, Matrix.Identity);
        }
        turn = MathHelper.Clamp(turn, -1, 1);
        collision.checkCollision(catBounding, hud);

        Vector3 movement = Vector3.Zero;
        catPosition.X = xTranslationPosition;
        catPosition.Y = yTranslationPosition;
        catPosition.Z = zTranslationPosition;
        //catPosition.Y = heightmap.getHeight(catPosition) + 10;
        //translatePosition = newPosition;
        camera.updateCamera(catPosition);

```

Drawing the object:

```
Matrix[] bones = animationCat.GetCatTransforms();
        Matrix rotationMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(180)) *
                                Matrix.CreateRotationZ(MathHelper.ToRadians(90));
        Matrix[] transforms = new Matrix[currentModel.Bones.Count];
        currentModel.Root.Transform = Matrix.CreateRotationY(MathHelper.ToRadians(-90));
        currentModel.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in currentModel.Meshes)
        {
            foreach (Effect effect in mesh.Effects)
            {
                if (effect is SkinnedEffect)
                {
                    SkinnedEffect thiseffect = effect as SkinnedEffect;
                    thiseffect.SetBoneTransforms(bones);
                    thiseffect.View = camera.getView;
                    thiseffect.Projection = camera.getProjection;
                    thiseffect.World = transforms[mesh.ParentBone.Index] *
                                       rotationMatrix *
                                       Matrix.CreateTranslation(xTranslationPosition, yTranslationPosition, zTranslationPosition);
                    catBounding = BoundingBox.CreateFromSphere(collision.CreateSphere(currentModel, thiseffect.World));

                }
            }
            mesh.Draw();
        }

```

And my camera class which I've borrowed from msdn sample for 3rd person camera.

```
public class GameCamera
{
    Matrix view;
    Matrix proj;

    Vector3 avatarHeadOffset = new Vector3(0, 10, 0);

    // Set the direction the camera points without rotation.
    Vector3 cameraReference = new Vector3(0, 0, 10);

    Vector3 thirdPersonReference = new Vector3(0, 200, -200);

    // Set field of view of the camera in radians (pi/4 is 45 degrees).
    static float viewAngle = MathHelper.PiOver4;

    // Set distance from the camera of the near and far clipping planes.
    //static float nearClip = 5.0f;
    static float nearClip = 1.0f;
    static float farClip = 2000.0f;

    public void updateCamera(Vector3 position)
    {
        Matrix rotationMatrix = Matrix.CreateRotationY(avatarYaw);

        // Create a vector pointing the direction the camera is facing.
        Vector3 transformedReference =
            Vector3.Transform(thirdPersonReference, rotationMatrix);

        // Calculate the position the camera is looking from.
        Vector3 cameraPosition = transformedReference + position;

        // Set up the view matrix and projection matrix.
        view = Matrix.CreateLookAt(cameraPosition, position,
            new Vector3(0.0f, 1.0f, 0.0f));

        Viewport viewport = Game1.graphics.GraphicsDevice.Viewport;
        float aspectRatio = (float)viewport.Width / (float)viewport.Height;

        proj = Matrix.CreatePerspectiveFieldOfView(viewAngle, aspectRatio,
            nearClip, farClip);
    }
}

```

As you can see here cat is very small and thats not the view I want to have. view from camera

# Answer
Here is a very easy & basic way to accomplish this:

```
//class scope variable in game class
Matrix catWorldMatrix;

//when drawing cat while setting effect params
//you effectively store the cat's rotation/position
//in the matrix catWorldMatrix which you will eventually allow the camera to use
catWorldMatrix = transforms[mesh.ParentBone.Index] *
                   rotationMatrix *
                   Matrix.CreateTranslation(xTranslationPosition, yTranslationPosition, zTranslationPosition);
thisEffect.World = catWorldMatrix;

//in camera update method
    public void updateCamera(Matrix objectToFollow)//send catWorldMatrix here
    {
        Vector3 target = objectToFollow.Translation; // camera always looks directly at cat
        Vector3 camPosition = target + objectToFollow.Backward * 10;//locates camera 10 units behind cat
        view = Matrix.CreateLookAt(camPosition, target, Vector3.Up);

    }

```

This methodology eliminates the need to rotate the camera's reference vectors. It simply borrows the rotation matrix from the cat (which is the same rotation you effectively want for the camera anyway) and uses it to create a new orthonormal view matrix.

If you want the camera to be slightly higher than the cat & looking past the cat, you simply modify it like this:

```
Vector3 target = objectToFollow.Translation + (objectToFollow.Up* heightOffset);
Vector3 camPosition = objectToFollow.Translation  + (objectToFolow.Backward * 10) + (objectToFollow.Up * heightOffset);

```
> 1 votes

---
Tags: xna, xna-4.0, camera, game-loop
---


# Question
Title: Help interpreting the physics of a rolling ball
I'm using this article for reference. I understand handling the collision aspect, but I can't figure out how to calculate the new velocity once the ball collides with the ramp. Without it the ball just slides down the slope and stops at the bottom, with no horizontal velocity generated from the descent.

The equation mentioned is

tangentialVelocity = velocity – (velocity * normal)normal

Which I've tried as

```
        ball.velocityX = _magnitude - (_magnitude * _normalX) * _normalX;
        ball.velocityY = _magnitude - (_magnitude * _normalY) * _normalY;

```

to no avail.

Here is what I've done so far, which finds how far the ball is intersecting in the ramp and moves it outside.

```
        var _distance:int = FP.distance(circleWorld.x, circleWorld.y, ball.x, ball.y);
        var _penetration:int = _distance + ball.radius - worldRadius;

        if (_penetration > 0)
        {
            var _componentX:int = circleWorld.x - ball.x;
            var _componentY:int = circleWorld.y - ball.y;

            var _normalX:Number = _componentX / _distance;
            var _normalY:Number = _componentY / _distance;

            ball.x += _normalX * _penetration;
            ball.y += _normalY * _penetration;
        }

```

# Answer
It doesn't look like your code is actually tracking the ball's rotation. The rotational inertia of the ball will have a very great effect on how quickly it descends the ramp, and how long it'll keep moving after it exits the ramp.

Some ideas for further thought here: http://physics.bu.edu/~duffy/sc527\_notes06/race.html

---

Edited to clarify: Your current simulation is modeling the ball *sliding* down a frictionless ramp. A real ball on a real ramp will likely not move at all without turning. You can calculate the forces on the ball using equations like those in the web page I linked to above. Once you know the torque on the ball, you can calculate how quickly it turns.

It'll roll down the ramp at approximately the same speed that it's rotating at, which is to say the distance travelled along the ramp in a given time will approximately equal the arc length that the perimeter rotates in the same time (some slippage will occur in a realistic situation).
> 2 votes

# Answer
> tangentialVelocity = velocity – (velocity * normal)normal

That is vector maths, the `*` in this case means dot product, both `velocity` and `normal` are vectors.

A dot product is calculated like so:

```
dotp = vector1.x * vector2.x + vector1.y * vector2.y

```

So your code should as best I can tell be this:

```
dotp = ball.velocityX * _normalX + ball.velocityY * _normalY
ball.velocityX -= dotp * _normalX;
ball.velocityY -= dotp * _normalY;

```

And for the sake of completeness `_normal` must of course be length 1 and pointing in the correct direction for this to work.
> 0 votes

---
Tags: physics
---


title: Repeatedly Shooting Bullets

text:
# Question
Title: Repeatedly Shooting Bullets
I'm making an XNA shooter game. How do I have my sprite repeatedly shoot bullets instead of waiting for one bullet to go off the screen. Do I do this with and array?

# Answer
> 1 votes
I imagine somewhere you have: `Bullet bullet;`

Then some methods such as:

```
ShootBullet(int x, int y)
{
  Bullet b = new Bullet(x, y);
}

Draw()
{
  b.Draw(SpriteBatch); //or SpriteBatch.Draw(b.tex, b.bounds, b.x, b.y)
}

Update()
{
    b.Update(); //or b.X += b.xAccel
}

```

Because of this, you are only allowing yourself one bullet at a time. What you want to do, since I imagine you aren't looking for the most efficient method, is to do the following.

`List<Bullet> bulletsOnScreen;`

In your constructor put:

`bulletsOnScreen = new List<Bullet>();`

Then do the following:

```
ShootBullet(x,y)
{
  Bullet b = new Bullet(x,y);
  bulletsOnScreen.Add(b);
}

Draw()
{
  foreach(Bullet b in bulletsOnScreen)
    b.Draw();
}

Update()
{
  foreach(Bullet b in bulletsOnScreen)
    b.Update();

  if(b.bounds.X > screen.X) //add more logic for being off screen
    bulletsOnScreen.Remove(b);
}

```

This will maintain a list of bullets you can keep track of, and when the bullet is no longer on screen (this is where you need to put in logic to determine if a bullet is off screen) it removes it from the list of bullets.

# Answer
> 0 votes
You could create a timer class, then invoke the timer so when it's finished, the timer allows the next bullet to be shot.

I'm pretty sure this would work Create a separate class named Timer and put this in it.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace (your namespace) {
class Timer
    {
        int TimeToDelay;
        int TimeElapsed;
        public bool IsTimerDone;

        public void StartTimer(GameTime gt, int AmountOfTime)
        {
            while (AmountOfTime < TimeElapsed)
            {
                IsTimerDone = false;
                TimeToDelay = AmountOfTime;
                if (IsTimerDone == false)
                {
                    if (TimeToDelay == gt.ElapsedGameTime.TotalSeconds)
                    {
                        IsTimerDone = true;

                    }
                    else TimeElapsed += 1;
                }
            }
        }
    }
}

```

Then Invoke the timer class in the main game class.

```
namespace (GameNameHere)
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /* DECLARE INIT VARIABLES */
    // Declare Timer
        Timer timer;
    Bool BulletReady = true;

        protected override void Initialize()
        {
            /* Init logic */

        // Create New Instance of The Timer
        timer = new Timer();

            base.Initialize();
        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

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

            // REPLACE CONTROL CODE WITH INVOKE/BUTTONPRESS HERE
            // if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed)
            // {
                if (BulletReady == true)
                {
                    if (timer.IsTimerDone == false)
                    {
                        // replace 1 with amount of time (in seconds)
                        timer.StartTimer(gameTime, 1);
                        BulletReady = false;
                    }
                    else if (timer.IsTimerDone == true)
                    {
                        BulletReady = true;
                    }

                }

                }
            // }

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

```

The bulletready boolean value is for so you can shoot again. If it is true, You can shoot, vice versa.

Basically, for the invoke, Create the timer's variable, Create a new instance in the initialization, Then in update, check for gamepad input, and if the bulletready is true, start a timer for the amount of time you want the bullet to be on cool down.

---
Tags: xna-4.0
---