title: How to build a "traffic AI"?

text:
# Question
Title: How to build a "traffic AI"?
A project I am working on right now features a lot of "traffic" in the sense of cars moving along roads, aircraft moving aroun an apron etc.

As of now the available paths are precalculated, so nodes are generated automatically for crossings which themselves are interconnected by edges. When a character/agent spawns into the world it starts at some node and finds a path to a target node by means of a simply A\* algorithm. The agent follows the path and ultimately reaches its destination. No problem so far.

Now I need to enable the agents to avoid collisions and to handle complex traffic situations. Since I'm new to the field of AI I looked up several papers/articles on steering behavior but found them to be too low-level. My problem consists less of the actual collision avoidance (which is rather simple in this case because the agents follow strictly defined paths) but of situations like one agent leaving a dead-end while another one wants to enter exactly the same one. Or two agents meeting at a bottleneck which only allows one agent to pass at a time but both need to pass it (according to the optimal route found before) and they need to find a way to let the other one pass first. So basically the main aspect of the problem would be predicting traffic movement to avoid dead-locks.

Difficult to describe, but I guess you get what I mean. Do you have any recommendations for me on where to start looking? Any papers, sample projects or similar things that could get me started?

I appreciate your help!

# Answer
There are so many ways of addressing this problem I'd struggle to give a decent and comprehensive answer here. But here are some high level design points.

* You're building an agent simulation here. Pathfinding is simply one input into the system - the agent has a goal, and path-finding is just a way it can achieve that goal. Actually, thinking of it in real terms the agent has two goals: a driver's foremost goal is "don't crash", second to that is "get where I want to go".
* Your systems should build on real world parallels. The reason why most roads have two or more lanes is because it's much easier to organise traffic with that system, no-one has to think very much. In a single lane scenario, drivers have to sort out various problems:

**detection** \- recognising that you and the oncoming car will crash unless you avoid each other

**reaction** \- slowing down and entering into a negotiation phase.

**negotiation** \- one of the drivers has to take the lead, the other has to yield. The rules for how to decide this are vague, but basically you want something where one driver arbitrarily (or based on a heuristic about how many cars are coming in the other direction) decides to take priority. E.g. A takes priority at time 1, B sees A take priority, and yields (by moving out of the way and stopping). If both A and B try to take priority, they should both stop, wait a random amount of time (or signal each other) and try again. Eventually one will yield to the other.

The beauty of this implementation is that it avoids the need to maintain artificial queues or other fake constructs. The negotiation is done in terms of real world perceptions - once both parties are in the negotiation phase, any significant forward motion is easily detected as an attempt to take priority. It should also react appropriately to the user, who will most likely not adhere to good driving rules.
* Assume the worst. Even in a perfect system, odd situations can come up, and your actors should act sensibly. This is even more likely if the player can interfere (artificially block off areas, etc.) Often, stopping altogether is the only sensible response (gridlock!) Spinning on the spot or obviously being in a broken state is a failure of AI. Stopping altogether is at least plausible in real world terms.

The closer you model your actor's AI on simple real world logic, the easier it will be to create convincing AI. Real people don't stop or oscillate back and forward if they can't reach their goal. If the only road to the AI's destination is blocked, they should recognise that and choose a response (stop altogether, give up and drive home, give up and drive elsewhere).
* Layer behaviours to get what you want. Remember, 1st goal is not to crash. So avoidance (steering) logic should always dominate the driver's actions. Layer on top of that the directional logic that comes from the path-finding ('I want to take a right at the next junction'). Layer on top of that occasional re-evaluation of paths, with higher level logic ('prefer to go forward, but if I can't make progress, allow a new path that involves a U-turn').
* Path-finding comes from memory, but situational awareness is based on perception. Don't try to make your agents perfect. They know the way from their home to the office, so they know which turns to make. But they don't know that the street 2 miles away is blocked. Don't try to make your agents plot a perfect path, because there are none - even if it starts out perfect, other factors may block their path. Agents should only need to plan a few streets ahead where they're going.
* Information quality. Your behaviours should be simple, but to achieve that you need good query functionality. You need to be able to ask questions of your environment like "is that oncoming car occupying my lane?", "how many cars are oncoming?", "are there any cars behind me", "can I do a U-turn".
> 12 votes

# Answer
Having seen some horrible failures in released games I have a couple of suggestions:

1) Unless there is a good reason otherwise make two lanes and for AI purposes make them have priority for a normal direction of flow--permit two-abreast travel but if something's coming the other way the guy on the wrong side of the road always yields to it.

2) Some sort of logic to unwind a traffic jam if it occurs. I've watched situations where the traffic jam handling only applied to the vehicles that were trying to run into each other but utterly failed when confronted with a -\> -\> \<- \<- pattern. I recall one map that was prone to this--it was a chokepoint meant to make the AI base harder to attack but sooner or later two resource harvesters would come in while an attack group was heading out and that was that. The units in contact would spin around trying to find a route out but they had no legal moves. It didn't backtrack and figure out that some other unit had to move first, and thus the AI took no useful actions until the roadblock was removed. (You could watch the units in contact spin around and nothing else do anything.)

I believe this could be solved by making a stuck unit tell neighboring units to get out of the way--this would propagate until it reached an unstuck unit that could back away. This would have to involve some sort of logic to keep them away until the problem was cleared.

Note that simply looking for an alternative path is often a bad answer. I've watched a livelock situation of that kind--unit A notes that B is blocking the road up ahead and so it turns around to use a different route. This now blocks the road for B who turns around--now the road is unblocked so both turn around again. Each turn they alternate between moving forward and moving backwards.

The same game I've seen a different version of it, also due to the fog of war. There was an enemy unit at a chokepoint. On auto-move the pathfinding would not fight unless actually targeted on the enemy unit. It would move forward and see the road was blocked. It then moved back, it could no longer see the blocker and it would move forward again. Repeat until the human realized it wasn't getting where it was supposed to go.
> 5 votes

# Answer
I'm not too experienced with traffic simulations, but a few things spring to mind.

Firstly, to prevent bottlenecks in the first place I would have two lanes that allow the vehicles to travel in opposite directions. on the same "road".

Secondly, for collisions that may occur, you *should* have a collision avoidance steering behaviour to prevent a massive pile up. Steering behaviours may be low level, but they're very useful in creating realistic looking emergent behaviour.

If you don't want to have more than one lane you're going to have to store more information in the graph. For example, if agent A is on a road (represented as a graph edge) and agent B is on the same road moving in the opposite direction to A then they *will* collide/deadlock/whatever you've coded to deal with this behaviour.

However, if agent A is on a road, it could request ownership of that road. Owning the road would mean that no other agent can travel along that edge (you could do this quite simply by changing the edge cost to a massive number to make sure A\* doesn't choose the road when calculating a path). Then when agent A is free of that road it relinquishes ownership.

Honestly, it's a hacky solution that I'm not particularly fond of and most traffic simulations (if not all?) that I've seen use a multi-lane approach.
> 4 votes

# Answer
You said you looked up several articles about steering behaviour, though just in case, have you looked up the following one?

http://www.red3d.com/cwr/steer/

If not, it might provide you some answers, as it covers some of the problems you named, for example the bottleneck problem (Queuing).
> 4 votes

# Answer
I think what you need to do is implement a path finding algorithm.

Break up your map into as small of pieces as you can (say squares) but only for valid places for traffic to travel. You would then determine where the vehicle is and where it is going and find a path, shortest or most direct perhaps. The path will be a array of squares, each step of the way to the destimation. What you would then want is to calculate not only the current position of all vehicles but the future positions of vehicles for a couple of steps in the future. If two vehicles are going to be in the same square in the future then you need to change the velocity of one or both of them.

A\* (A star) is a very simple path finding algorithm that you can probably just easily translate the psuedo code in wikipedia into your language of choice and it will work: http://en.wikipedia.org/wiki/A\*\_search\_algorithm
> 0 votes

# Answer
When I implemented Enemy Nations my final fall-back was that if a vehicle was stuck for over 2 seconds, I jumped it forward on its path. So when they got stuck a unit basically transported. No one ever complained so I figure the few times it happened no one was watching and didn't see it.
> 0 votes

---
Tags: ai, movement
---


# Question
Title: Can I develop 2D tower defense game with unit3D in C# for Android?
I tried to find the answer in unity3d site but without success. If the answer to my question is yes, does anyone know where I can find an example?

# Answer
> 0 votes
of course you can, nothing is impossible. some things are just darn hard. And you are not going to find perfect examples of HOW to do specific games unfortunately.

# Answer
> 4 votes
No.

My reasoning is this: if you could develop a 2D tower defense game, you wouldn't have taken time out from developing a 2D tower defense game in order to ask us whether you could develop the 2D tower defense game you were already developing.

Hope this helps.

---
Tags: c#, android, unity, tower-defense
---


# Question
Title: HTML5 platformer collision detection problem
I'm working on a 2D platformer game, and I'm having a lot of trouble with collision detection. I've looked trough some tutorials, questions asked here and Stackoverflow, but I guess I'm just too dumb to understand what's wrong with my code.

I've wanted to make simple bounding box style collisions and ability to determine on which side of the box the collision happens, but no matter what I do, I always get some weird glitches, like the player gets stuck on the wall or the jumping is jittery. You can test the game here: **Platform engine test**. Arrow keys move and z = run, x = jump, c = shoot. Try to jump into the first pit and slide on the wall.

Here's the collision detection code:

```
function checkCollisions(a, b)
{
    if  ((a.x > b.x + b.width) ||
        (a.x + a.width < b.x) ||
        (a.y > b.y + b.height) ||
        (a.y + a.height < b.y))
    {
        return false;
    }
    else
    {
        handleCollisions(a, b);
        return true;
    }
}

function handleCollisions(a, b)
{
    var a_top = a.y,
        a_bottom = a.y + a.height,
        a_left = a.x,
        a_right = a.x + a.width,
        b_top = b.y,
        b_bottom = b.y + b.height,
        b_left = b.x,
        b_right = b.x + b.width;

        if (a_bottom + a.vy > b_top && distanceBetween(a_bottom, b_top) + a.vy < distanceBetween(a_bottom, b_bottom))
        {
            a.topCollision = true;
            a.y = b.y - a.height + 2;
            a.vy = 0;
            a.canJump = true;
        }
        else if (a_top + a.vy < b_bottom && distanceBetween(a_top, b_bottom) + a.vy < distanceBetween(a_top, b_top))
        {
            a.bottomCollision = true;
            a.y = b.y + b.height;
            a.vy = 0;
        }

        else if (a_right + a.vx > b_left && distanceBetween(a_right, b_left) < distanceBetween(a_right, b_right))
        {
            a.rightCollision = true;
            a.x = b.x - a.width - 3;
            //a.vx = 0;
        }
        else if (a_left + a.vx < b_right && distanceBetween(a_left, b_right) < distanceBetween(a_left, b_left))
        {
            a.leftCollision = true;
            a.x = b.x + b.width + 3;
            //a.vx = 0;
        }

}
function distanceBetween(a, b)
{
    return Math.abs(b-a);
}

```

# Answer
You shouldn't be checking every block stored in collisionMap.

it is many times more faster only detecting blocks around the player by indexing the original tile map.

To check if you are standing on a tile:

1. You get the player X,Y co-ordinate
2. Add the player height to Y.
3. Divide this X, Y by tile width, height
4. Index the original map data and get the tile
5. check if tile == "n" to determine if are standing on anything or not.

You do this twice, once for the bottom left hand side of the player and once on the bottom right hand side of the player.

Code is rough and some variables are just made up but names give clue to what is what:

```
 // returns true if there is a tile other than "n"
 function collided(x, y) {
     return game.currentLevel.map[y >> 5][x >> 5] != "n";
 }

 // Collision for standing...
 var bottomY = playerY + playerHeight;
 var isStanding = collided(playerX, bottomY) || collided(playerX + playerWidth, bottomY);

 // if isStanding is true then you've got to stop falling
 // The % 32 part ensures the player feet lands perfectly on the tile Y boundary
 if (isStanding) {
    playerY = (bottomY  % 32) - playerHeight;
    // set other stuff here such as canJump and velocityY = 0, e.t.c.
 }

```

You repeat this for left / right and top of the player.

Note: Your character height is higher than 32 pixels so you probably need to do 3 calls to collided, one for top, one for midway down, and one for bottom

Added more info:

```
 function collided(x, y) {
     return game.currentLevel.map[y >> 5][x >> 5] != "n";
 }

```

is the same as

```
 function collided(x, y) {
     return game.currentLevel.map[Math.floor(x / 32)][Math.floor(y / 32)] != "n";
 }

```

This \>\> means rotate the bits X number of times.

32 is a power of 2 number, i.e. it is a bit in binary, for this reason, rather than doing divide by 32, you can do \>\> 5 instead.

The advantage of doing this is the rotating bits is far faster at machine level than doing a divide and you also do not have to worry about rounding.

32 in binary is 00010000

So, if you 000010000 \>\> 5 Becomes 00000001

which is the same as 32 / 32 = 1

If you want to learn more, search for bitwise rotation
> 4 votes

---
Tags: collision-detection, javascript, html5, html-canvas
---


# Question
Title: How to shade a texture two different colors?
To give an example of what I'm asking about, I'll use Saints Row 3 since I've been playing that lately. In that game you can customize your looks and your car's appearance a lot. Your coat can have a primary color and a trim color. Your car can have a primary color and a stripe color, etc.

Is there just a single coat texture that is being shaded two different colors somehow or are they overlaying a transparent second texture for the trim/stripes that gets shaded differently?

If it's just one texture I'd like to know how it's done.

If it's two different textures it seems like it's a waste of space. The second texture would be the same size as the first one but mostly transparent if you just wanted to lay it on top of the first one. Or are they just carefully positioning a second, smaller texture so that it aligns properly with the first one?

# Answer
There are a number of possible approaches.

It can be done with a single texture. Options include creating a texture for that specific car/player based on the source images at runtime, or if it's a relatively solid color, they might instead map a primary color to red, a secondary color to green, and then remap those colors in a pixel shader. Alternatively they might pack that information into an alpha channel, for example mapping opposite sides of 0.5 to different tints, while still handling non-solidly colored objects with the remaining RGB channels. Pixel shaders would be doing the magic in this case.

Multiple textures are also possible -- it's already common to have diffuse, specular, and normal map textures all on the same object. Both approaches -- a large transparent fourth texture on top of the others and lining up with them, or a decal texture separately positioned on the mesh from the others, are viable. In the latter case it'll likely share the same geometry, just with different UV coordinates, and if drawn as a separate draw call / pass, it will likely also not include any geometry it isn't applied to.

**tl;dr:** Yes, those are all options, which one a given game uses will likely be up to their tools and workflow, their standards, or even simple artist preference.

**edit:** Here's a link on how EVE Online has their textures set up:, if you want to dig into a specific system http://community.eveonline.com/devblog.asp?a=blog&bid=732
> 1 votes

# Answer
First I think it's important to hammer down some terminology. When geometry is rendered with a texture, the texture is not "shaded." Shading the process of coloring the geometry. The texture is used in the shading calculations. With that in mind, I can get to the core of your question.

It depends on how the shader is written. For an asset that has customizable color, the base color can be passed in as the vertex color, and then blended with the texture lookup to derive the final color of the pixel. This is also the cheapest way of accomplishing what you're asking about, since it then doesn't require extra texture memory, and only costs a little more data to be sent to the GPU. Certain parts of the car can be shaded using different materials (if you consider a material to be the combination of several textures and a shader program). Of course, this requires that the car be made of several separate meshes, which may not be ideal.

For a game as large and graphically intense as Saints Row, the car likely has several other textures associated with it, such as diffuse maps, normal maps, light maps, etc. All of these are blended together using different techniques to compute the final look of the surface.

That "using different techniques" part is what brings me back to how I began my question: it all depends on how the shader is written, and how the model is created.

One other possibility is that there is a texture associated with a car which would be called an alpha map. The lookup values in this map can be used such that the fragment of the car is shaded with the primary color if the alpha is 0, and the trim color is used if the alpha is 1. Such a computation might look like this:

```
float alpha = textureLookup(alphaMap, fragmentCoords).a;
vec4 primaryColor = vertexColor * (1.0 - alpha);
vec4 trimColor = vertexColor * (alpha);
FragColor = primaryColor + trimColor;

```

This is a bit of a crude GLSL-style example, but I think it demonstrates what I'm describing. Assuming it's feasible to incur the extra texture memory cost to store the alpha map, then this method can be useful.
> 1 votes

---
Tags: textures, shaders
---


# Question
Title: Is opengl ES a necessity for developping mobile games
I learned some OpenGL ES and some shader coding. But is it really a necessity for developing Android, iOS and windows phone games? Windows phone I'm 99% sure that it is not even supported but have not researched it yet.

# Answer
Speaking to Android specifically, there is a 2D drawing API available as documented here that is not OpenGL ES based: http://developer.android.com/guide/topics/graphics/2d-graphics.html

If you aren't specifically looking to avoid OpenGL ES entirely and are just looking for a convenient abstraction on top of it to prevent you from having to work with it directly there are more options. For instance, while I haven't used it personally, starting with Android 3.0/API 11 it is possible to use hardware acceleration for the aforementioned 2D API: http://developer.android.com/guide/topics/graphics/hardware-accel.html

It does use OpenGL ES "under the sheets" but you wouldn't need to concern yourself with the details and/or create custom shaders. If this is acceptable you might also want to consider something like AndEngine: http://www.andengine.org/

With iOS, you probably want to check out their documents on Quartz 2d: https://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq\_overview/dq\_overview.html

In terms of 3D, there are libraries that can buffer you from OpenGL ES a bit. I used the Irrlicht port for API level 8/2.2 a few years ago although it looks a bit dusty now: http://gitorious.org/irrlichtandroid/pages/Home

You might consider libgdx: http://libgdx.badlogicgames.com/
> 3 votes

# Answer
When you want to create 2d games, then no, you won't need it.

When you want to do 3d games, you should first consider the available 3d engines and do a cost/benefit analysis of creating your own 3d engine. In most cases, this analysis will tell you that using an existing engine will allow you to bring your game to market in a lot less man-hours.

Every software developer has the urge to reinvent the wheel. But most of the time it's wasted effort, because others have already done it better than you could ever do it, and they offer it for a fraction of the price it would cost you to repeat their work. An important skill for every software developer is the ability to suppress ones pride, and realize when it's more efficient to buy an existing solution instead of inventing an own.

But note that "free" solutions aren't really cost-neutral: you still need to invest time and money to understand their API and integrate it into your project. An expensive one which comes with good documentation and support can turn out to be cheaper than a free one with poor documentation and without professional support.
> 1 votes

---
Tags: android, ios, windows-phone-7
---


# Question
Title: Low-level GPU code and Shader Compilation
Bear with me, because I will raise several questions at once. I still feel, though, that overall this can be treated as one question that may be answered succinctly.

I recently dove into solidifying my understanding of the assembly language, low-level memory operations, CPU structure, and program optimizations. This also sparked my interest in how higher-level shading languages, GLSL and HLSL in particular, are compiled and optimized, as well as what formats they are reduced to before machine code is generated (assuming they are not converted directly into machine code).

After a bit of research into this, the best resource I've found is this presentation from ATI about the compilation of and optimizations for HLSL. I also found sample ARB assembly code.

This sort of addressed my original curiosity, but it raised several other questions. The assembler code in the ATI presentation seems like it contains instructions specifically targeted for the GPU, but is this merely a hypothetical example created for the purpose of conceptual understanding, or is this code really generated during shader compilation? If so, is it possible to inspect it, or even write it in place of the higher-level syntax? My initial searches for an answer to the last question tell me that this may be disallowed, but I have not dug too deep yet.

Also, along the same lines, are GLSL shader programs compiled into ARB assembly code before machine code is generated, and is it possible to write direct ARB assembly?

Lastly, and perhaps what I am most interested in finding out: are there comprehensive resources on shader compilation and low-level GPU code? I have been unable to find any thus far.

I ask simply because I am curious :)

# Answer
> 6 votes
> The assembler code in the ATI presentation seems like it contains instructions specifically targeted for the GPU, but is this merely a hypothetical example created for the purpose of conceptual understanding, or is this code really generated during shader compilation?

PIX and other vendor-specific graphical debugging tools can show you the assembly code your HLSL breaks down into. You can also use these assembly instructions (various versions of which are documented here). The presentation you linked seems to focus mostly on the ps\_2\_0 version of this assembly language. Compiling HLSL into this vendor-agnostic assembly code is handled by Microsoft's libraries (D3DX I believe) which is then given to the driver via D3D to further process into vendor/gpu-specific code (labeled in the presentation as microcode... I'm inclined to believe they haven't faked the one snippet of ATI microcode they've shown, but that's just a guess.)

> If so, is it possible to \[...\] even write it in place of the higher-level syntax?

You may be able to write your own bytecode (either through encoding it manually yourself or using asm {} blocks for some targets), but it's discouraged, at least for production. Harder to read, forces you to rewrite to take advantage of the latest opcodes, not even allowed in more modern versions of HLSL, etc. Getting a handle on what your HLSL ends up turning into is all fine and dandy, of course.

> Also, along the same lines, are GLSL shader programs compiled into ARB assembly code before machine code is generated, and is it possible to write direct ARB assembly?

GLSL has generally been compiled directly by vendor specific drivers, lacking an official GLSL-to-bytecodes compiler and a driver model forcing people to use it, resulting in some unfortunate variation where some vendors will compile GLSL that others won't. Similarly, they may or may not compile to ARB as an intermediate step -- it wouldn't surprise me if they translate both GLSL and ARB assembly directly into some vendor-specific intermediate representation before giving it to the underlying kernel-land driver and ultimately the GPU.

Vendors and vendor tools are ultimately going to be the ultimate authority on how their GPUs will perform at a low level. They have a vested interest in providing game developers with the tools they need to make their games perform well on their hardware. Check them out and dig in:

https://developer.nvidia.com/tools

http://developer.amd.com/tools/graphics-development/

---
Tags: shaders, glsl, hlsl, gpu
---


# Question
Title: How can I create a fast, real-time, fixed length glowing ray?
Similar to the disintegrate skill in Diablo 3. It should not light other objects in scene. Just glowing and animated. Like in this video http://www.youtube.com/watch?v=D\_c4x6aQAG8.

Should I use pack of pre-computed glow sources textures for each frame of ray animation like in this article http://http.developer.nvidia.com/GPUGems/gpugems\_ch21.html and put it in bloom shader?

Is there any other efficient ways to achive this effect? I'm using OpenGL ES 2.0.

# Answer
> 2 votes
Yes, you should try implementing it the way you suggest.

Another way would be to create the animated ray in an art program. Export it to a sprite sheet and just use a textured quad to display the animation where you need it. That would be very efficient.

# Answer
> 0 votes
If your camera will always see the ray almost perpendicular you can use just one large quad, but if you want volume when seen from other angles try using three or four intersecting large quads. This quads intersect in the middle of the quad (if seen from actor perspective we should see an star like structure).

Take a look at the wire-frame near the thrusters, those polygons are used to create a kind-of-volumetric-effect there. http://cdn1.eveonline.com/www/newssystem/media/2954/3217/10.jpg

---
Tags: opengl-es, glow, bloom
---


title: SFX Played Once per Collision or Hit

text:
# Question
Title: SFX Played Once per Collision or Hit
I have a question about using Box2D (engine for LibGDX used to make realistic physics). I observed on the code that I've made for the physics here below:

```
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
      // TODO Touch Up Event

     if(is_Next_Fruit_Touched)
     {
             BodyEditorLoader Fruit_Loader = new BodyEditorLoader(Gdx.files.internal("Shape_Physics/Fruity Physics.json"));

             Fruit_BD.type = BodyType.DynamicBody;
             Fruit_BD.position.set(x, y);

             FixtureDef Fruit_FD = new FixtureDef(); // --> Allows you to make the object's physics.
             Fruit_FD.density = 1.0f;
             Fruit_FD.friction = 0.7f;
             Fruit_FD.restitution = 0.2f;

             MassData mass = new MassData();
             mass.mass = 5f;

             Fruit_Body[n] = world.createBody(Fruit_BD);
             Fruit_Body[n].setActive(true); // --> Let your dragon fall.
             Fruit_Body[n].setMassData(mass);
             Fruit_Body[n].setGravityScale(1.0f);

             System.out.println("Eggs... " + n);

             Fruit_Loader.attachFixture(Fruit_Body[n], Body, Fruit_FD, Fruit_IMG.getWidth());
             Fruit_Origin = Fruit_Loader.getOrigin(Body, Fruit_IMG.getWidth()).cpy();

             is_Next_Fruit_Touched = false;
             up = y;
             Gdx.app.log("Initial Y-coordinate", "Y at " + up);

             //Once it's touched, the next fruit will set to drag.
             if(n < 50)
             {
                 n++;

             }else{

                 System.exit(0);

             }
     }

         return true;

```

}

Now, I'm thinking which part o line should I implement for the sound effects. My objectives to make SFX played once for every collision (Or should I say "SFX played once per collision"?) on the following:

* *SFX played once if they hit on the objects of its kind. (e.g. apple vs. apple)*
* *SFX played once on a different sound when it hit on the ground. (e.g. apple land on the mud)*

Take note that I'm using **Box2D for the Java programming version** thanks to *LibGDX* via *Box2D* engine and I edited the physics body using *Physics Body Editor* before I implement it to code.

I tried to check every available methods for body, fixture definition, or body definition to code for the SFX when hit but it seems only for the gravity and weight. Is there possibly available on the document for SFX played when collision happens if possible?

# Answer
I don't really see how all that physics code is relevant to playing SFX. (Although you do need collision detection to decide when to play sounds.)

The following design is all pseudocode

In your Apple class body...

```
function onCollisionWith(otherThing)
    if     type(otherThing) == "apple" then playSound("bonk!") end
    elseif type(otherThing) == "mud"   then playSound("splat!") end
end

```

In your collision detection code...

```
thisObjectCurrentlyBeingCheckedFor
    .onCollisionWith(thatObjectItWasFoundToCollideWith)

```

This would produce a sound effect whenever the two objects are colliding.

Depending on how your physics handles the collision, you may want to introduce some state to describe what objects it was *already* colliding with last frame, so you don't re-play the sound.
> 1 votes

---
Tags: java, collision-detection, physics, libgdx, sound-effects
---


# Question
Title: Android, apply a pixelshader on a canvas
Can an opengl pixelshader be applied on a Canvas?

I want to render a bitmap on a canvas, then apply a pixelshader to get, for example, a blur effect. Is this possible?

I don't want to simulate the blur effect by creating a new bitmap and then blur this from java code because i'd like to be able to re-use the shaders in openGL apps too.

# Answer
Yes and no, take a look at this article: http://www.xenomachina.com/2011/05/androids-2d-canvas-rendering-pipeline.html You can use an opengl pixelshader but there are other ways to attain the same.
> 1 votes

---
Tags: android, opengl-es, opengl-es2
---


# Question
Title: Is it possible to load local html pages into Gamemaker games?
I was just wondering if it would be possible somehow to load locally saved web pages into a game. My primary use for them would be as menus, helping to navigate between rooms.

I know about the built in "Open URL" function but I want to know if the loaded page can interact with the actual game.

# Answer
> 1 votes
No. (Certainly not without external DLLs anyway.)

HTML is only a mark-up language — to actually see a page, you need an HTML renderer. Game Maker doesn't have one.

It would be possible to open a locally rendered web page in a browser and use local storage to save files to disk which you could then load from Game Maker, but that's a *really* long way around!

Consider making your own menus, using an existing menu system like this one or learning to make web-based games.

---
Tags: html5, web, game-maker
---


# Question
Title: Character jump animation is not working when I hit the space bar
I am having an issue with my game in XNA. My jump sprite sheet for my character does not trigger when I hit the space bar. I can't seem to find the problem. I have also include the code below to make things easier.

```
namespace WindowsGame4
{

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        // start of new code
        Texture2D playerWalk; // sprite sheet of walk cycle (14 frames)
        Texture2D idle; // idle animation
        Texture2D jump; // jump animation
        Vector2 playerPos; // to hold x and y position info for the player
        Point frameDimensions; // to hold width and height values for the frames
        int presentFrame; // to record which frame we are on at any given time
        int noOfFrames; // to hold the total number of frames in the spritesheet
        int elapsedTime; // to know how long each frame has been shown
        int frameDuration; // to hold info about how long each frame should be shown
        SpriteEffects flipDirection; // SpriteEffects object
        int speed; //rate of movement
        int upMovement;
        int downMovement;
        int rightMovement;
        int leftMovement;
        int jumpApex;
        string state; //this is going to be "idle","walking" or "jumping".
        KeyboardState previousKeyboardState;
        Vector2 originalPlayerPos;
        Vector2 movementDirection;
        Vector2 movementSpeed;

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

        protected override void Initialize()
        {
            // textures will be defined in the LoadContent() method
            playerPos = new Vector2(0, 200); // starting position for the player is at the left of the screen, and a Y position of 200
            frameDimensions = new Point(55, 65); // each frame in the idle sprite sheet is 55 wide by 65 high
            presentFrame = 0; // start at frame 0
            noOfFrames = 5; // there are 5 frames in the idle cycle
            elapsedTime = 0; // set elapsed time to start at 0
            frameDuration = 80; // 80 milliseconds is how long each frame will show for (the higher the number, the slower the animation)
            flipDirection = SpriteEffects.None; // set the value of flipDirection to none
            speed = 200;
            upMovement = -2;
            downMovement = 2;
            rightMovement = 1;
            leftMovement = -1;
            jumpApex = 100;
            state = "idle";
            previousKeyboardState = Keyboard.GetState();
            originalPlayerPos = Vector2.Zero;
            movementDirection = Vector2.Zero;
            movementSpeed = Vector2.Zero;

            base.Initialize();
        }

        protected override void LoadContent()
        {

            spriteBatch = new SpriteBatch(GraphicsDevice);
            playerWalk = Content.Load<Texture2D>("sprites/walkSmall"); // load the walk cycle spritesheet
            idle = Content.Load<Texture2D>("sprites/idleCycle"); // load the idle cycle sprite sheet
            jump = Content.Load<Texture2D>("sprites/jump"); // load the jump cycle sprite sheet
        }

        protected override void UnloadContent() // we're not using this method at the moment
        {
        }

        protected override void Update(GameTime gameTime) // Update method - used it to call a number of other methods
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                this.Exit(); // Exit the game if the Escape key is pressed
            }
            KeyboardState presentKeyboardState = Keyboard.GetState();
            UpdateMovement(presentKeyboardState, gameTime);
            UpdateIdle(presentKeyboardState, gameTime);
            UpdateJump(presentKeyboardState);
            UpdateAnimation(gameTime);
            playerPos += movementDirection * movementSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
            previousKeyboardState = presentKeyboardState;
            base.Update(gameTime);
        }

        private void UpdateAnimation(GameTime gameTime)
        {
            elapsedTime += gameTime.ElapsedGameTime.Milliseconds;
            if (elapsedTime > frameDuration)
            {
                elapsedTime -= frameDuration;
                elapsedTime = elapsedTime - frameDuration;
                presentFrame++;
                if (presentFrame > noOfFrames)
                    if (state != "jumping")
                    {
                        presentFrame = 0;
                    }
                    else
                    {
                        presentFrame = 8;
                    }
            }
        }

        protected void UpdateMovement(KeyboardState presentKeyboardState, GameTime gameTime)
        {
            if (state == "idle")
            {
                movementSpeed = Vector2.Zero;
                movementDirection = Vector2.Zero;
                if (presentKeyboardState.IsKeyDown(Keys.Left))
                {
                    state = "walking";
                    movementSpeed.X = speed;
                    movementDirection.X = leftMovement;
                    flipDirection = SpriteEffects.FlipHorizontally;
                }
                if (presentKeyboardState.IsKeyDown(Keys.Right))
                {
                    state = "walking";
                    movementSpeed.X = speed;
                    movementDirection.X = rightMovement;
                    flipDirection = SpriteEffects.None;
                }
            }
        }

        private void UpdateIdle(KeyboardState presentKeyboardState, GameTime gameTime)
        {
            if ((presentKeyboardState.IsKeyUp(Keys.Left) && previousKeyboardState.IsKeyDown(Keys.Left)
                || presentKeyboardState.IsKeyUp(Keys.Right) && previousKeyboardState.IsKeyDown(Keys.Right)
                && state != "jumping"))
            {
                state = "idle";
            }

        }

        private void UpdateJump(KeyboardState presentKeyboardState)
        {
            if (state == "walking" || state == "idle")
            {
                if (presentKeyboardState.IsKeyDown(Keys.Space) && !presentKeyboardState.IsKeyDown(Keys.Space))
                {
                    presentFrame = 1;
                    DoJump();
                }
            }
            if (state == "jumping")
            {
                if (originalPlayerPos.Y - playerPos.Y > jumpApex)
                {
                    movementDirection.Y = downMovement;
                }
                if (playerPos.Y > originalPlayerPos.Y)
                {
                    playerPos.Y = originalPlayerPos.Y;
                        state = "idle";
                    movementDirection = Vector2.Zero;
                }
            }
        }

        private void DoJump()
        {
            if (state != "jumping")
            {
                state = "jumping";
            originalPlayerPos = playerPos;
            movementDirection.Y = upMovement;
            movementSpeed = new Vector2(speed, speed);
            }
        }

        protected override void Draw(GameTime gameTime) // Draw method
        {

            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(); // begin the spritebatch
            if (state == "walking")
            {
                noOfFrames = 14;
                frameDimensions = new Point(55, 65);
                Vector2 playerWalkPos = new Vector2(playerPos.X, playerPos.Y - 28);
                spriteBatch.Draw(playerWalk, playerWalkPos, new Rectangle((presentFrame * frameDimensions.X), 0, frameDimensions.X, frameDimensions.Y), Color.White, 0, Vector2.Zero, 1, flipDirection, 0);
            }
            if (state == "idle")
            {
                noOfFrames = 5;
                frameDimensions = new Point(55, 65);
                Vector2 idlePos = new Vector2(playerPos.X, playerPos.Y - 28);
                spriteBatch.Draw(idle, idlePos, new Rectangle((presentFrame * frameDimensions.X), 0, frameDimensions.X, frameDimensions.Y), Color.White, 0, Vector2.Zero, 1, flipDirection, 0);
            }
            if (state == "jumping")
            {
                noOfFrames = 9;
                frameDimensions = new Point(55, 92);
                Vector2 jumpPos = new Vector2(playerPos.X, playerPos.Y - 28);
                spriteBatch.Draw(jump, jumpPos, new Rectangle((presentFrame * frameDimensions.X), 0, frameDimensions.X, frameDimensions.Y), Color.White, 0, Vector2.Zero, 1, flipDirection, 0);
            }
            spriteBatch.End(); // end the spritebatch commands
            base.Draw(gameTime);
        }
    }
}

```

# Answer
In `UpdateJump` this seems wrong, doesn’t it?

```
if (presentKeyboardState.IsKeyDown(Keys.Space)
    && !presentKeyboardState.IsKeyDown(Keys.Space))

```

Guess you meant to use `previousKeyboardState`:

```
if (presentKeyboardState.IsKeyDown(Keys.Space)
    && !previousKeyboardState.IsKeyDown(Keys.Space))

```
> 1 votes

---
Tags: xna, 2d, animation, spritesheet, character
---


# Question
Title: How can I repeat only a portion of an image in Javascript?
So I'm trying to repeat a *portion* of my spritesheet as a background. So far, I have attempted this:

```
var canvas = $("#board")[0],
    ctx = canvas.getContext("2d"),
    sprite = new Image();
    sprite.src = "spritesheet.png";
sprite.onload = function(){
    ctx.fillStyle = ctx.createPattern(spriteBg, "repeat");
    ctx.fillRect(0, 25, 500, 500);
}

```

As you can see, it repeat the whole image, not just a part of it, and I just can't figure out how to do that last part.

# Answer
> 0 votes
This'll do! :D

```
var sprite     = new Image(),
    sprite.src = "spritesheet.png",
    texture    = {y: 42, x: 2*14},
    ptrn       = generatePattern(sprite, texture.x, texture.y);
ctx.fillStyle  = ctx.createPattern(ptrn, "repeat");
ctx.fillRect(0, 0, 500, 500);

```

Thanks to @KeithThomas for linking to https://stackoverflow.com/questions/8761670/multiple-image-patterns-in-2d-context-of-html5-canvas

---
Tags: javascript, html5, html-canvas
---


title: Setting a leader from a sprite array

text:
# Question
Title: Setting a leader from a sprite array
I'm looking to set a leader from an array of sprites, I keep on getting a NullReferenceException was unhandled error from within my main game class when calling the UpdateMouse Method. What have I dont wrong here?

```
class MouseSprite
{

    Random random = new Random();
    private MouseSprite leader;

    public void UpdateBoundaryBox()
    {
        mouseBounds.X = (int)mousePosition.X - mouseTexture.Width / 2; mouseBounds.Y = (int)mousePosition.Y - mouseTexture.Height / 2;
    }

    public void UpdateMouse(Vector2 position, MouseSprite [] mice, int numberMice, int index)
    {

        Vector2 catPosition = position;
        int enemies = numberMice;
        this.alive = true;

        mice[random.Next(0, mice.Length)] = leader;

```

# Answer
`leader` is uninitialized. I assume you're trying to pick a random leader, not set the leader to some mouse randomly (overwriting the mouse stored there with `null`). You want to swap your assignment statement.

```
leader = mice[random.Next(0, mice.Length)];

```
> 0 votes

# Answer
Null reference exceptions are thrown because you are trying to access to a reference typed variable that is not assigned.

In the UpdateMouse method code, the only candidate to throw that exception is the array, that maybe is not assigned, check it.
> -1 votes

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


# Question
Title: Reversi/Othello early-game evaluation function
I've written my own Reversi player, based on the MiniMax algorithm, with Alpha-Beta pruning, but in the first 10 moves my evaluation function is too slow. I need a good early-game evaluation function.

I'm trying to do it with this matrix (corresponding to the board) which determines how favourable that square is to have:

```
   { 30, -25, 10, 5, 5, 10, -25,  30,},
   {-25, -25,  1, 1, 1,  1, -25, -25,},
   { 10,   1,  5, 2, 2,  5,   1,  10,},
   {  5,   1,  2, 1, 1,  2,   1,   5,},
   {  5,   1,  2, 1, 1,  2,   1,   5,},
   { 10,   1,  5, 2, 2,  5,   1,  10,},
   {-25, -25,  1, 1, 1,  1, -25, -25,},
   { 30, -25, 10, 5, 5, 10, -25,  30,},};

```

But it doesn't work well.

Have you even written an early-game evaluation function for Reversi?

# Answer
> 3 votes
I see you've already figured out the positional strategy.

One very simple heuristic that works pretty good early in the game is "give-away", aka "evaporation": boards that have *more* enemy stones and *fewer* of your stones are better. (This is a little counter-intuitive, because the opposite is true at the end of the game).

So a simple board evaluation function could be something like

```
early_game := (total_stones < 40)
if( early_game ){
    // give-away in the early game
    count_goodness := K1*( enemy_stones - friendly_stones )
}else{
    // take-back later in the game
    count_goodness := K2*( friendly_stones - enemy_stones )
}
positional_goodness = K3*position_matrix_evaluation;
total_board_goodness = count_goodness + positional_goodness

```

where K1, K2, and K3 are tweaked to make it "play well".

You may want to glance over the Strategy Guide for Reversi & Reversed Reversi for more complicated heuristics.

# Answer
> 3 votes
In many board games, it is common for the first 'n' moves to be pre-calculated into an "opening book", which is just a file containing all the possible game positions within that number of moves, and the preferred responses to take for each.

To generate the opening book you use the same heuristic as you do for normal play, but instead of doing it on the fly while the game is being played, you calculate all possible moves within those first 'n', and store the results into a file that you ship with the game. Then when the game is actually playing, for those first 'n' moves, instead of running the heuristic (which as you say, can be quite slow), you instead look up the pre-calculated results from the opening book you saved out earlier.

---
Tags: java, algorithm, ai
---


title: Square game map rendered as sphere

text:
# Question
Title: Square game map rendered as sphere
For a hobby project of mine I have created a finite voxel world (similar to Minecraft), but as I said, mine is finite. When you reach the edge of it, you are sent to the other side. That is all working fine along with rendering the far side of the map, but I want to be able to render this grid as a sphere.

Looking down from above, the world is a square. I basically want to be able to represent a portion of that square as a sphere, as if you were looking at a planet. Right now I am experimenting with taking a circular section of the map, and rendering that, but it look to flat (no curvature around the edges).

My question then, is what would be the best way to add some curvature to the edges of a 2d circle to make it look like a hemisphere. However, I am not overly attached to this implementation so if somebody has some other idea for representing the square as a planet, I am all ears.

# Answer
> 6 votes
Right now you essentially have a 2D plane, or at least a thick sheet of cubes. That's your map. You want to take that map and wrap it around a sphere. An easy way to do that is to convert your wrapping coordinates into spherical coordinates. Wrapping the same way you would with your current world.

To avoid all the nasty warping effects you get from this conversion at the poles, I would also shift the wrapping so that your player is always on the equator of the sphere.

This can be done entirely in the shader if you like. This keeps things very simple because it's an effect you can just turn on or off and you don't have to worry about changing any of your game logic.

I did a little experimenting with this myself and the above is the method I used. The results were promising:

# Answer
> 2 votes
Use the same sort of approach used in Populous III -- just trick the eye as you zoom out. That way you can keep your planar world model, which is easy to work with.

---
Tags: opengl, rendering, voxels
---


title: openGL textures in bitmap mode

text:
# Question
Title: openGL textures in bitmap mode
For reasons detailed here I need to texture a quad using a bitmap (as in, 1 bit per pixel, not an 8-bit pixmap).

Right now I have a bitmap stored in an on-device buffer, and am mounting it like so:

```
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, BFR.G[(T+1)%2]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, W, H, 0, GL_COLOR_INDEX, GL_BITMAP, 0);

```

The OpenGL spec has this to say about glTexImage2D: *"If type is GL\_BITMAP, the data is considered as a string of unsigned bytes (and format must be GL\_COLOR\_INDEX). Each data byte is treated as eight 1-bit elements..."*

Judging by the spec, each bit in my buffer should correspond to a single pixel. **However, the following experiments show that, for whatever reason, it doesn't work as advertised:**

1) When I build my texture, I write to the buffer in 32-bit chunks. From the wording of the spec, it is reasonable to assume that writing 0x00000001 for each value would result in a texture with 1-px-wide vertical bars with 31-wide spaces between them. However, it appears blank.

2) Next, I write with 0x000000FF. By my apparently flawed understanding of the bitmap mode, I would expect that this should produce 8-wide bars with 24-wide spaces between them. Instead, it produces a white 1-px-wide bar.

3) 0x55555555 = 1010101010101010101010101010101, therefore writing this value ought to create 1-wide vertical stripes with 1 pixel spacing. However, it creates a solid gray color.

4) Using my original 8-bit pixmap in GL\_BITMAP mode produces the correct animation.

**I have reached the conclusion** that, even in GL\_BITMAP mode, the texturer is still interpreting 8-bits as 1 element, despite what the spec seems to suggest. The fact that I can generate a gray color (while I was expecting that I was working in two-tone), as well as the fact that my original 8-bit pixmap generates the correct picture, support this conclusion.

**Questions:**

1) Am I missing some kind of prerequisite call (perhaps for setting a stride length or pack alignment or something) that will signal to the texturer to treat each byte as 8-elements, as it suggests in the spec?

2) Or does it simply not work because modern hardware does not support it? (I have read that GL\_BITMAP mode was deprecated in 3.3, I am however forcing a 3.0 context.)

3) Am I better off unpacking the bitmap into a pixmap using a shader? This is a far more roundabout solution than I was hoping for but I suppose there is no such thing as a free lunch.

# Answer
While you could probably get this to work, I would say the best answer is choice #3, for several reasons.

1) GL\_BITMAP is actually not deprecated in 3.3, it is full on *removed*. If you are doing OpenGL 3.+, I strongly advise against using deprecated functionality.

2) It is probably not going to be super fast on today's hardware anyway. (although I have no benchmarks to back this up, but I assume it is fixed-functionality that is probably emulated by the driver.)

So I would just do it in the shader. You should be able to bit shift based on texture co-ordinates, or unless texture memory is very constrained, you could probably get away with 8 bits per pixel, having 0x00 as 0 and 0xFF as 1.

If you really want to keep going along the current route, you could try using the compatibility profile instead of core.
> 2 votes

---
Tags: opengl
---


# Question
Title: Bullet Physic: Transform body after adding
I would like to transform a rigidbody after adding it to the btDiscreteDynamicsWorld. When I use the **CF\_KINEMATIC\_OBJECT** flag I am able to transform it but it's static (no collision response/gravity). When I don't use the **CF\_KINEMATIC\_OBJECT** flag the transform doesn't gets applied. So how to I transform non-static objects in bullet?

---

**DemoCode:**

```
btBoxShape* colShape = new btBoxShape(btVector3(SCALING*1,SCALING*1,SCALING*1));

/// Create Dynamic Objects
btTransform startTransform;
startTransform.setIdentity();

btScalar mass(1.f);

//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);

btVector3 localInertia(0,0,0);
if (isDynamic)
    colShape->calculateLocalInertia(mass,localInertia);

btDefaultMotionState* myMotionState = new btDefaultMotionState();
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia);

btRigidBody* body = new btRigidBody(rbInfo);
body->setCollisionFlags(body->getCollisionFlags()|btCollisionObject::CF_KINEMATIC_OBJECT);
body->setActivationState(DISABLE_DEACTIVATION);

m_dynamicsWorld->addRigidBody(body);

startTransform.setOrigin(SCALING*btVector3( btScalar(0), btScalar(20), btScalar(0) ));

body->getMotionState()->setWorldTransform(startTransform);

```

# Answer
I solved it by using **body-\>setWorldTransform(startTransform);** and not **body-\>getMotionState()-\>setWorldTransform(startTransform);**. I also removed the Kinematic flag and the deactivation.
> 2 votes

---
Tags: c++, bullet-physics, transformation
---


title: Bukkit send a custom placed name plate?

text:
# Question
Title: Bukkit send a custom placed name plate?
Hello i have been working on a part of my plugin that has waypoints allowing the user to create delete etc. I got to thinking after using and seeing a couple of the disguse plugins. That maybe i could create a command toggle that would show the user where the waypoints they have are! I know how to do all of this i just have no idea how to display a nameplate to the client. I know its possible because disguisecraft does it i tried looking though their code but couldent find much...

I belive to get this effect i need to send packets to the client if someone can direct me to a list of bukkit packets or even a solution to sending the client a custom located nameplate that would be fantastic! Thanks in advanced.

# Answer
I'm not exactly sure what you mean about a custom nameplate, but DisguiseCraft (which I'm a developer of) uses Bukkit's display name function. We merely used `player.setDisplayerName("NewName")` so that players appeared to have the new names and could talk in the chat with them.
> 1 votes

# Answer
Yes, DisguiseCraft uses packets to change the name of a player or remove the name tag. The 'player.setDisplayName' function only changes the name that will appear in chat, not the nameplate above the player entity. I'm not entirely sure what the code would look like, but from what I understand you want actual floating name tags with the name of the waypoint. My idea would be to spawn named entities, making them invisible somehow, and making them not move from the waypoint location. You could also change the color of the nameplate to make it easier for players to distinguish from a normal player name tag and a waypoint.
> 0 votes

# Answer
It's technically not possible to hide the nameplates without hiding the person, changing nameplates requires skin changes as it sends packets to fool the client into believing another player is where the real player is. UNLESS you hook into something like the spoutcraft API or another client-side mod.
> 0 votes

# Answer
Alright first of all:

```
player.setDisplayerName("NewName")

```

Where would you put it at in the first place, it's not going to be:

```
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
Player player = (Player) sender;

```

Maybe:

```
}if(args.length == 0){
    player.setDisplayerName(ChatColor.BLUE + player.getName());

```

And basically keep doing the args until it's enough:

```
 args[0] + " " + args[1] + " " + args[2] + " " + args[3] + " " + args[4] + " " + args[5] + " " + args[6] + " " + args[7] + " " + args[8] + " " + args[9] + " " + args[10] + " " + args[11] + " " + args[12] + " " + args[13] + " " + args[14] + " " + args[15]);

```
> -1 votes

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


# Question
Title: How can I pass an array of floats to the fragment shader using textures?
I want to map out a 2D array of depth elements for the fragment shader to use to check depth against to create shadows. I want to be able to copy a float array into the GPU, but using large uniform arrays causes segfaults in openGL so that is not an option. I tried texturing but the best i got was to use GL\_DEPTH\_COMPONENT

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 512, 512, 0, GL_DEPTH_COMPONENT, GL_FLOAT, smap);

```

Which doesn't work because that stores depth components (0.0 - 1.0) which I don't want because I have no idea how to calculate them using the depth value produced by the light sources MVP matrix multiplied by the coordinate of each vertex.

Is there any way to store and access large 2D arrays of floats in openGL?

# Answer
To pass big amounts of data for random access using textures is the correct way. Setting large amounts of uniforms is very slow and you only have a very limited amout of constant registers on most hardware.

You can use GL\_R32F or GL\_DEPTH\_COMPONENT32F as a texture format, which has to be supported by your target hardware, to store a single single precision floating point value per sample.

A shadow map texture is normally done using a normalized depth between the near and far planes of your shadow light, eg by using the depth value after projective divide. This gives you are higher precision, fixed point textures are often more efficient than floating point textuers and are supported by a wider range of hardware.
> 8 votes

---
Tags: opengl, shaders
---


title: 2D Smooth Turning in a Tile-Based Game

text:
# Question
Title: 2D Smooth Turning in a Tile-Based Game
I am working on a 2D **top-view** grid-based game. A ball that rolls on the grid made up of different tiles. The tiles interact with the ball in a variety of ways.

I am having difficulty cleanly implementing the turning tile. The image below represents a single tile in the grid, which turns the ball by a right angle.

If the ball rolls in from the bottom, it smoothly changes direction and rolls to the right. If it rolls in from the right, it is turned smoothly to the bottom. If the ball rolls in from top or left, its trajectory remains unchanged by the tile.

The tile shouldn't change the magnitude of the velocity of the ball - only change its direction.

The ball has Velocity and Position vectors, and the tile has Position and Dimension vectors.

I have already implemented this, but the code is messy and buggy. What is an elegant way to achieve this, preferably by modification of the ball's Velocity vector by a formula?

# Answer
> 6 votes
I assume you know how to find out when the ball enters that specific tile. Based on which side the ball enters the tile, you should move it until the ball leaves that specific tile. Based on your problem, when you detect the ball entered from top or left edge, you just let it move without changing it's velocity at all. Let's assume the ball enters from right edge, you should make the ball move on a quarter of a circle. There are two possible scenarios:

1. if you are not using a physics engine for ball movement, or you don't mind setting ball position, you should just use a temporary variable `theta` and increase it based on the time passed, here is the exact formula:

```
theta += delta_time * (Ball_speed / Circle_radius)
position = circle_center + circle_radius * vec2(sin(theta), cos(theta))

```

in which `circle_radius` is equal to half of your grid width, and `circle_center` in your example is the right bottom corner of tile
2. if you are using a physics engine and you don't want to mess with it, you should apply force to keep the ball on the track. in this case you should compute acceleration in every update which is also simple, based on this formula:

```
acceleration = (Circle_center - Ball_position) * (Ball_speed ^ 2) / (circle_radius ^ 2)

```

this time `circle_radius` is the distance between ball position and circle center. I know it should be equal to half block size, but due to all kinds of computation errors the ball might move out of it's path a little bit, and using dynamic distance helps just a little. still I recommend setting ball position forcefully when it's going to go out of that tile.

In case the ball enters from bottom edge, in the first method you should decrease theta instead of increasing it every frame. but you don't need to change anything in the second method.

---
Tags: mathematics, physics
---


title: Lightweight sprite animation software

text:
# Question
Title: Lightweight sprite animation software
Does anyone know of a good lightweight sprite animator solution? I've created a couple of spritesheets using TexturePacker, but I'd like to, for example, create an XML file that tells me frames one through three are part of animation X, and frames 4 through 6 are part of animation Y.

I am primarily a OSX developer.

# Answer
I haven't used it personally, yet, but I've heard good things about spriter: http://www.brashmonkey.com/spriter.htm
> 1 votes

---
Tags: animation, sprites, spritesheet
---


# Question
Title: How should I organise classes for a space simulator?
I have pretty much taught myself everything I know about programming, so while I know how to teach myself (books, internet and reading API's), I'm finding that there hasn't been a whole lot in the way of good programming.

I am finishing up learning the basics of XNA and I want to create a space simulator to test my knowledge. This isn't a full scale simulator, but just something that covers everything I learned. It's also going to be modular so I can build on it, after I get the basics down. One of the early features I want to implement is AI. And I want to take this into account as I'm designing my classes so I can minimize rewriting code.

So my question: How should I design ship classes so that both the player and AI can use them?

The only idea I have so far is:

Create a ship class that contains stats, models, textures, collision data etc. The player and AI would then have the data for position, rotation, health, etc and would base their status off of the ship stats.

# Answer
> 5 votes
As mentioned in you comments you're already on the right track, It's becoming increasingly common to break game entities down into 'components', if you wanted a really clear explanation of component based game development this article is commonly referenced and considered a good solid guide still: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

But re-structuring like that is not necessary for your needs and don't worry if you want to keep it simple.

I did a very similar thing in a very simple 2 player snake game with optional AI, when i created a new `Snake`, I passed it a `Controller` in the constructor, I had two children of the Controller parent class, a `PlayerController` that could handle keyboard input and an `AIController` that had a timer that allowed it to fire certain behavior every X seconds to change its direction and such. It meant that at run time I could decide what sort of controller to make and give to a snake based on player input/setting. This had other benefits too, reusing the same entities but dynamically changing their behavior is obviously favorable.

---
Tags: xna, architecture
---


# Question
Title: How do I call functions that take more than one frame to finish?
I'm trying to figure out how to implement C# scripting into my XNA game. How do I call functions that take more than one frame to finish?

For example:

```
class UserScript : Script
{
    public override void execute(Game game)
    {
        //script must wait for dialog to be closed
        game.openDialog("This is a dialog");

        //script should'nt wait for this
            int goldToGive = 100;
            goldToGive += 100;
            game.addGold(goldToGive);
        //

        //script should wait for cinematic to end
        game.startCinematic("name_of_cinematic");

        //doesn't wait
        game.addGold(100);
    }
}

```

I found a question that suggests you can do it with `yield`, but I'm not sure if it's the correct way, as the referenced article is from 2010, and no longer exists. Is using `yield` the answer? If so, how do I use it? If not, should I take a differant approach, or am I better off with multi-threading?

# Answer
You can find the mentioned article in the internet archive: The magic of yield.
As mentioned in the conclusion of the article, you don't have to return a "float", but rather a custom type that you can query for all sorts of results.
In the case of your dialog (and in the same way for your cinematic), you can write something like:

```
Dialog dialog = game.openDialog("This is a dialog");
while (dialog.isOpen) {
    yield return 1f;
}
//Continue script...

```
> 2 votes

# Answer
Since yield is just generating a state machine for you, you can just as easily roll your own and implement a bunch of tasks to be executed in some sort of collection. Or use yield and use the results for something (time to wait, state to be in, etc.). Good discussion about all this with some images can be found here: https://stackoverflow.com/questions/5923767/simple-state-machine-example-in-c
> 1 votes

# Answer
Consider using reflection instead. You can provide dlls with classes to call and types/interfaces to uYpse. Users can compile code and drop dlls in a particular folder for you to load at runtime. Same for content.
> 0 votes

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


# Question
Title: How to force a garbage collector swep on libgdx?
I found that you can control your memory usage on libgdx with:

```
int javaHeap = Gdx.app.getJavaHeap();
int nativeHeap = Gdx.app.getNativeHeap();

```

But, How can I force a garbage collector cleanup? I want to force in special moments, like screen change on a game.

# Answer
> 6 votes
Java's garbage collector is nondeterministic. There's `System.gc();` but it will likely do nothing. See the StackOverflow question for further discussion.

# Answer
> 2 votes
Many of the libgdx classes have memory allocated across JNI. Destroying/disposing of classes should handle this for you. Forcing a GC call may not be de-allocating classes if they reside in native managed memory. Last time I used libgdx, it provided decent logs of when memory was allocated/destroyed. Do yo have a specific issue when loading new screens?

**Update**: Based on this page, there's a screen.dispose() and comments suggesting that you should reuse your screen class to avoid GC.

# Answer
> 2 votes
While you can give a hint to the runtime engine via System.gc() this is a "hint" and not a command so you cannot rely on it to actually trigger garbage collection. Even if it were a command, forcing garbage collection is unlikely to accomplish what you want- the garbage collection process itself consumes resources so when it runs your game will be impacted. So, in fact, you want to avoid garbage collection to ensure your game isn't contending with the GC process for resources, see this link for a libgdx specific discussion: http://code.google.com/p/libgdx-users/wiki/ForceGarbageCollection

Instead of dynamically allocating many short lived objects that require garbage collection I think the better strategy would be to allocate long life objects at times the user isn't playing, e.g. loading screen or first start up. These objects can even be returned to a pool when no longer needed and then reused as necessary.

---
Tags: libgdx, memory-efficiency
---


# Question
Title: Collision Detection algorithms with early Collision exit
I'm using collision detection in Monte Carlo simulations and at the moment I'm using GJK which is quite fast. I can't help to think it could be done even faster though. In the simulations, about 70% of the time GJK is run, it detects a collision. Thus collisions are more than non-collisions in my case. Most collision detection algorithms I know have an early non-collision exit test.

Are there any collision detection algorithms that have an early collision detect instead of non-collision and could be potentially faster than GJK in case of collision?

# Answer
> 1 votes
I think this case is unusual because generally the non collision case is more common and because the user of the collision detection test needs additional information when a hit is reported (contact point, normal, parametric sweep amount) and that wouldn't be available in the early out case.

That said you could easily imagine doing a faster test with primitives that are inwardly conservative (i.e. sphere vs. sphere where each sphere is completely contained inside its respective GJK primitive)

---
Tags: collision-detection
---


# Question
Title: How do I make a jumping dolphin rotate realistically?
I want to program a dolphin that jumps and rotates like a real dolphin. Jumping is not the problem, but I don't know how to make the rotation. At the moment, my dolphin rotates a little weird. But I want that it rotates like a real dolphin does.

How can I improve the rotation?

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D image, water;
    float Gravity = 5.0F;
    float Acceleration = 20.0F;
    Vector2 Position = new Vector2(1200,720);
    Vector2 Velocity;
    float rotation = 0;
    SpriteEffects flip;
    Vector2 Speed = new Vector2(0, 0);

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

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        image = Content.Load<Texture2D>("cartoondolphin");
        water = Content.Load<Texture2D>("background");
        flip = SpriteEffects.None;
    }

    protected override void Update(GameTime gameTime)
    {
        float VelocityX = 0f;
        float VelocityY = 0f;

        float time = (float)gameTime.ElapsedGameTime.TotalSeconds;
        KeyboardState kbState = Keyboard.GetState();
        if(kbState.IsKeyDown(Keys.Left))
        {
            rotation = 0;
            flip = SpriteEffects.None;
            VelocityX += -5f;
        }

        if(kbState.IsKeyDown(Keys.Right))
        {
            rotation = 0;
            flip = SpriteEffects.FlipHorizontally;
            VelocityX += 5f;
        }

        // jump if the dolphin is under water
        if(Position.Y >= 670)
        {
            if (kbState.IsKeyDown(Keys.A))
            {
                if (flip == SpriteEffects.None)
                {
                  rotation += 0.01f;
                  VelocityY += 40f;
                }
                else
                {
                  rotation -= 0.01f;
                  VelocityY += 40f;
                }
            }
        }
        else
        {
            if (flip == SpriteEffects.None)
            {
              rotation -= 0.01f;
              VelocityY += -10f;
            }
            else
            {
              rotation += 0.01f;
              VelocityY += -10f;
            }
        }

        float deltaY = 0;
        float deltaX = 0;

        deltaY = Gravity * (float)gameTime.ElapsedGameTime.TotalSeconds;

        deltaX += VelocityX * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration;
        deltaY += -VelocityY * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration;

        Speed = new Vector2(Speed.X + deltaX, Speed.Y + deltaY);
        Position += Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        Velocity.X = 0;

        if (Position.Y + image.Height/2 > graphics.PreferredBackBufferHeight)
            Position.Y = graphics.PreferredBackBufferHeight - image.Height/2;

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(water, new Rectangle(0, graphics.PreferredBackBufferHeight -100, graphics.PreferredBackBufferWidth, 100), Color.White);
        spriteBatch.Draw(image, Position, null, Color.White, rotation, new Vector2(image.Width / 2, image.Height / 2), 1, flip, 1);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

---

The code now works almost perfectly. I introduced the bool variable direction and made some tests with the angle. Jumping works now as it should. But I couldn't change two things:

1)At the beginning(you can see it in the video), the dolphin always looks up. I want that it looks at the right side, if possible. I tried to change the rotation but it didn't worked.

2)The second thing is a little bit strange. If I change the direction from left to right or right to left, the dolphin is rotated in the wrong direction during a short moment. How can I fix that? I made a new video: http://www.myvideo.de/watch/8881567

```
    public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D image, water;
    float Gravity = 5.0F;
    float Acceleration = 20.0F;
    Vector2 Position = new Vector2(1200,720);
    Vector2 Velocity;
    float rotation = 0;
    SpriteEffects flip;
    Vector2 Speed = new Vector2(0, 0);
    bool direction = false;
    Vector2 prevPos;

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

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        image = Content.Load<Texture2D>("cartoondolphin");
        water = Content.Load<Texture2D>("background");
        flip = SpriteEffects.None;
    }

    protected override void Update(GameTime gameTime)
    {
        float VelocityX = 0f;
        float VelocityY = 0f;

        float time = (float)gameTime.ElapsedGameTime.TotalSeconds;
        KeyboardState kbState = Keyboard.GetState();
        if(kbState.IsKeyDown(Keys.Left))
        {
            flip = SpriteEffects.FlipHorizontally;
            VelocityX += -5f;
            direction = false;
        }

        if(kbState.IsKeyDown(Keys.Right))
        {
            flip = SpriteEffects.None;
            VelocityX += 5f;
            direction = true;
        }

        if (direction == false)
             {
          rotation = -((float)Math.Atan2(Position.X - prevPos.X, Position.Y - prevPos.Y) + MathHelper.PiOver2);
          prevPos = Position;
             }
        if (direction == true)
        {
            rotation = -((float)Math.Atan2(Position.X - prevPos.X, Position.Y - prevPos.Y) + MathHelper.Pi + MathHelper.PiOver2);
            prevPos = Position;
        }

        // jump if the dolphin is under water
        if(Position.Y >= 670)
        {
            if (kbState.IsKeyDown(Keys.A))
            {
                if (flip == SpriteEffects.None)
                {
                  VelocityY += 40f;
                }
                else
                {
                  VelocityY += 40f;
                }
            }
        }
        else
        {
            if (flip == SpriteEffects.None)
            {
              VelocityY += -10f;
            }
            else
            {
              VelocityY += -10f;
            }
        }

        float deltaY = 0;
        float deltaX = 0;

        deltaY = Gravity * (float)gameTime.ElapsedGameTime.TotalSeconds;

        deltaX += VelocityX * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration;
        deltaY += -VelocityY * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration;

        Speed = new Vector2(Speed.X + deltaX, Speed.Y + deltaY);

        Position += Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;

        Velocity.X = 0;

        if (Position.Y + image.Height/2 > graphics.PreferredBackBufferHeight)
            Position.Y = graphics.PreferredBackBufferHeight - image.Height/2;

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(water, new Rectangle(0, graphics.PreferredBackBufferHeight -100, graphics.PreferredBackBufferWidth, 100), Color.White);
        spriteBatch.Draw(image, Position, null, Color.White, rotation, new Vector2(image.Width / 2, image.Height / 2), 1, flip, 1);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

# Answer
# Intuition

A jumping dolphin's rotation is related to the direction it's moving.

The blue is water.
The dots are dolphin positions at each time tick.
The arrows are the direction the dolphin is rotated to face.

That bottom one is a radioactive dolphin with gravity powers.

# Implementation

You could get the same effect with something like this:

```
function dolphin.onPositionChange ()
    dolphin.sprite.rotation = directionFromTo(dolphin.prevPos, dolphin.pos)
    prevPos = pos
end

```

That's only illustrative pseudocode of course. Here's what it does in English:

```
Every time the dolphin's position changes
    The angle from its previous position to new position becomes its rotation
    The current position is saved as the old one, for use again next step

```

Finding the direction from point A to point B is a little bit of geometry. XNA might have a function that does this for you. **If it does, use that!**

# Theory

If it doesn't (or if you just want to understand what's going on), here's the geometry for you:

Love2D (my favourite game framework) doesn't have a function to calculate the direction from point to point. Here's how I made one:

```
-- Vector direction
-- Angle in radians, clockwise from up i.e. straight up is 0, right is
-- pi/2, down is pi, etc.
function directionFromTo(a,b)
    return math.atan2( (b.x - a.x) , (b.y - a.y) )
end

-- Test; should print 135
a = {x = 0, y = 0}
b = {x = 1, y = -1}
print( directionFromTo(a,b) / math.pi*180) -- (division to convert to degrees)

```
> 27 votes

---
Tags: xna, c#, animation, sprites
---


title: Difficulties with rotation of a sprite

text:
# Question
Title: Difficulties with rotation of a sprite
> **Possible Duplicate:**
> How do I make a jumping dolphin rotate realistically?

I want to program a dolphin that jumps and rotates like a real dolphin. Jumping is not the problem, but I don't know how to make the rotation. My dolphin always rests in the same angle while it jumps. But I want that it changes the rotation during the jump, like a real dolphin does. How can I improve the rotation?

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D image, water;
    float Gravity = 5.0F;
    float Acceleration = 20.0F;
    Vector2 Position = new Vector2(1200,720);
    Vector2 Velocity;
    float rotation = 0;
    SpriteEffects flip;
    Vector2 Speed = new Vector2(0, 0);

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

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        image = Content.Load<Texture2D>("cartoondolphin");
        water = Content.Load<Texture2D>("background");
        flip = SpriteEffects.None;
    }

    protected override void Update(GameTime gameTime)
    {
        float VelocityX = 0f;
        float VelocityY = 0f;

        float time = (float)gameTime.ElapsedGameTime.TotalSeconds;
        KeyboardState kbState = Keyboard.GetState();
        if(kbState.IsKeyDown(Keys.Left))
        {
            rotation = 0;
            flip = SpriteEffects.None;
            VelocityX += -5f;
        }

        if(kbState.IsKeyDown(Keys.Right))
        {
            rotation = 0;
            flip = SpriteEffects.FlipHorizontally;
            VelocityX += 5f;
        }

        // jump if the dolphin is under water
        if(Position.Y >= 670)
        {
            if (kbState.IsKeyDown(Keys.A))
            {
                if (flip == SpriteEffects.None)
                {
                  rotation = 45;
                  VelocityY += 40f;
                }
                else
                {
                  rotation = -45;
                  VelocityY += 40f;
                }
            }
        }
        else
        {
            VelocityY += -10f;
        }

        float deltaY = 0;
        float deltaX = 0;

        deltaY = Gravity * (float)gameTime.ElapsedGameTime.TotalSeconds;

        deltaX += VelocityX * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration;
        deltaY += -VelocityY * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration;

        Speed = new Vector2(Speed.X + deltaX, Speed.Y + deltaY);

        Position += Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;

        Velocity.X = 0;

        if (Position.Y + image.Height/2 > graphics.PreferredBackBufferHeight)
            Position.Y = graphics.PreferredBackBufferHeight - image.Height/2;

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(water, new Rectangle(0, graphics.PreferredBackBufferHeight -100, graphics.PreferredBackBufferWidth, 100), Color.White);
        spriteBatch.Draw(image, Position, null, Color.White, MathHelper.ToRadians(rotation), new Vector2(image.Width / 2, image.Height / 2), 1, flip, 1);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

# Answer
Increase the rotation, don't set it.

`rotation += 0.01f`

Although as someone already mentioned, not the best place for this question.
> 0 votes

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


title: Game Engines with real time lighting

text:
# Question
Title: Game Engines with real time lighting
I am studying computer graphics since 3 semesters and we just started with OpenGL. I really enjoy it and want to create my own little engine for learning purposes.

I already read tons of different forum posts and saw the following engines. Panda3d, Ogre3d, NeoAxis, Irrlicht and Horde3d(graphics only).

Now I don't want to use something like Unity or CryEngine because I want to start more low level.

Which of those engines is suited for real-time rendering? Something that CryEngine offers -\> no baked lightmaps.

Or at least gives me the option to add a real-time renderer?

# Answer
All of the engines you've listed are or already contain real-time renderers, because that is what a game engine must contain, by definition. A game must run at a framerate of at least 24 frames per second (for the perception of smooth motion), and for more intense, action filled games, that framerate requirement goes up to 60. Those framerates are synonymous with real-time.

The alternative to real-time is offline rendering, in which frames may take anywhere from one second to hours to render, and are recorded and then played back at a real-time rate. This is not suitable for games because of the need for interactivity.

If you are really interested in starting low-level and creating a small engine, then you would want to start with OpenGL. Trying to add features to already hefty engines like Panda3D can be difficult without a solid background in game engine architecture. That said, though, I would still recommend starting higher-level, with something like Unity, simply to familiarize yourself with already existing engines, and to help formulate ideas for the architecture and functionality of your own engine you'd like to create.
> 5 votes

---
Tags: rendering, ogre, panda3d
---


title: Integrating game center into cocos2d

text:
# Question
Title: Integrating game center into cocos2d
I have a Cocos 2d game in which I want to have achievements and a leader-board. What are the steps I would need to take?

Thanks

P.S All of the tutorials I have found are outdated. So please write instructions

# Answer
> 1 votes
It would be useful to know how far in the process you are.

If you haven't already registered your app and set up your leaderboards and achievements through iTunes Connect, then you should read through this tutorial.

If you have, then let us know exactly what you're stuck on.

---
Tags: cocos2d-iphone, ios, cocos2d, game-center
---


title: Concept: Interpretive Spells

text:
# Question
Title: Concept: Interpretive Spells
The goal is to be able to create complex spells, that can manipulate the game's environment in non-preprogrammed ways, and to make the program understand spells. For example:

```
$@

$=Big
@=Fire

```

You can probably understand what this one means. The player types, writes, or selects symbols. Of course, a spell can be only a few characters, or more sophisticated spells could potentially be hundreds or thousands of symbols long.

How could something like this be accomplished?

# Answer
This can be done via programming! As in, for example, Dungeon Master, released way back in 1987, which used exactly this magic system.

There's no trick to this sort of thing. If the user picks "fire", then "big" makes the effect larger. You can do this by a multiplier, by a static amount, by scaling up the area of effect, or whatever. There's no AI involved at all. Just a matter of taking user input and doing something sensible in response to that input.
> 7 votes

# Answer
To me it seems you want to deal with the rules of grammars (contextfree, context-sensitive, whatever) which are e.g. also used for designing programming languages.

Then you could define rules for which spells might follow which other spells or which modifiers. This is checked on **syntax** (correctness according to the rules) first.

Grammars look like this (I will not make it as formal as it is usually, because it might frighten you)

* We always start with `[spell]`
* We can replace `[spell]` with `[sizeof] [basic_spell]`
* We can also replace `[spell]` with `[spell], [spell]` (making to spells in a row)
* We can replace `[spell]` with `[basic_spell]`
* We can repeat these rules several times

This would be a valid grammar and say we have the following basic\_spells: **fire, water, light**

And these modifiers (sizeof): **small, big, short, long**

We could do something like this:

```
small fire, long water
small fire, water
big water

```

But illegal would be something like `big short water`. Or also `angry fire`, because there is no word `angry` in our set.

Of course you can replace the long words with single characters.

Later you will have to check it for **semantics** (meaning), e.g. if somebody uses a fire spell and then a water spell, it would reduce the overall power of the spell (Baten Kaitos uses this system). So `big fire, small water` would reduce the power of this spell, because water stops fire.

One the whole you could search for how programming languages are designed, because creating a new syntax for spells is nothing different. Maybe start with finding out how brainfuck works and search for how compilers or interpreters for brainfuck are programmed. As far as I know it's usually a few steps:

* checking if all characters are valid
* checking if the order of characters and words is valid (e.g. `foo int` is not valid in Java, but `int foo` is)
* building a tree from the code
* traversing that tree to generate the basic commands (in your case the desired spell combination)

Might not be totally correct, as I am not a compiler-programmer.

Depending on how difficult your syntax shall be, you can leave out some of the commands. E.g. my upper example was totally linear. You only had to check if the spell is **valid** and if it was, combine adjectives and nouns and then execute all commands in a row.

But in programming languages we also have `if`-conditions and loops (`for`, `while`), which leads to non-linear situations. Thus we need a tree which shows us how stuff is related.

In your situation one could think of spells like `4($!)` which might mean: Do the spell `$!` **four times**.

So you see, it's pretty much parsing a programming language.
> 3 votes

---
Tags: ai, user-generated-content
---


title: Vector vs Scalar velocity?

text:
# Question
Title: Vector vs Scalar velocity?
I am revamping an engine I have been working on and off on for the last few weeks to use a directional vector to dictate direction; this way I can dictate the displacement based on a direction. However, the issue I am trying to overcome is the following problem; the speed towards X and speed towards Y are unrelated to one another. If gravity pulls the object down by an increasing velocity my velocity towards the X should not change. This is very easy to implement if my speed is broken into a Vector datatype, Vector.X dictates one direction Vector.Y dictates the other (assuming we are not concerned about the Z axis). However, this defeats the purpose of the directional vector because:

```
  SpeedX = 10
  SpeedY = 15

  [1, 1] normalized = ~[0.7, 0.7]

  [0.7, 0.7] * [10, 15] = [7, 10.5]

```

As you can see my direction is now "scaled" to my speed which is no longer the direction that I want to be moving in.

I am very new to vector math and this is a learning project for me. I looked around a little bit on the internet but I still want to figure out things on my own (not just look at an example and copy off it). Is there way around this? Using a directional vector is extremely useful but I am a little bit stumped at this problem. I am sorry if my mathematical understanding maybe completely wrong.

# Answer
> 6 votes
\[Obligatory link to They Might Be Giants' "Speed and Velocity", which covers the basic concepts of this issue. And is probably a catchier tune than it has any right to be.\]

The gist:

* Speed is a scalar value stating how fast something is moving.
* Velocity is a vector value stating how fast something is moving **and** in what direction.

Velocity can be expressed as a normalised (ie: unit length) vector and a scalar 'speed', but for games it's normally much easier to just store the two multiplied together into a single velocity vector.

Once you're storing your velocity as a scaled vector, you can adjust the vertical component separately from the horizontal component. For example, to apply gravity, you will normally just add `gravity * time` (or `-gravity`, depending on which direction your y axis goes and whether you express gravity as a positive or negative number).

If you are using velocity in this way, then you do not normally store speed at all. If you need to do a calculation involving speed, you instead calculate it from the velocity by finding the velocity vector's length.

---
Tags: xna, mathematics
---


title: Why does Unity3D crash in VirtualBox?

text:
# Question
Title: Why does Unity3D crash in VirtualBox?
I'm running Unity3D in a virtual instance of Windows, using the Virtual Box software on Linux. I have guest additions installed with DirectX support. I've tried using Windows XP SP3 32-bit, and Windows 7 64bit. My host is Ubuntu 12.04 64bit.

I installed and registered Unity on both. It loads up fine, and then crashes my entire VirtualBox instance (equivalent of a computer shutting off with no warning).

# Answer
> 9 votes
According to the Unity forums, Unity will not work with Virtual Box.

It does however work with VMWare with the "Accelerate 3D graphics" option checked.

# Answer
> 6 votes
unity3d 4 works on virtual box as well - you need to enable 3d/2d support - 256MB video memory and install the virtualbox Direct3d driver while in windows safe mode

---
Tags: unity, virtual-machines
---


# Question
Title: How to change screen resolution in slick2d?
I released my game for testing for both windows and mac. I'm using mac as my development workspace. My friends uses windows and the window was to big. I created a 1000\*1500 Screen window. I can change the window size but that means I have to re-do all my sprite sheets again with smaller sheets. I don't want to this again but is there a way which I can make the window smaller without changing the size of my sprite and changing co-ordinates of the mouse clicks?

# Answer
> 3 votes
Use a ScaleableGame like this:

```
AppGameContainer agc = new AppGameContainer(
            new ScalableGame(INSERT YOUR GAME INSTANCE HERE,1000,1500));
agc.setDisplayMode(W,H,false);

```

Where `W` and `H` are the width and height of the actual window. Using this method your app will think that it is running at 1000x1500, but it will actually be running at WxH. All graphics output and mouse input etc. will be scaled accordingly, so you just program as if it is 1000x1500. Couldn't be simpler when you know how, eh?

---
Tags: java, slick
---


title: What are the statements in XNA?

text:
# Question
Title: What are the statements in XNA?
A hypothetical game called “AlienShooter” needs to be able to work on Windows and on the Xbox. In the Windows version, the keyboard will handle firing at alien spaceships, and this functionality is contained within a method called “KeyboardSupport()”. In the Xbox version of the game, the gamepad will be used for shooting, and this functionality is contained within a method called “GamepadSupport()”. Write the statement(s) that must be added so that the appropriate code is used in the each version of the game.

# Answer
Use the #if directive:

```
#if WINDOWS
  KeyboardSupport();
#elif XBOX
  GamepadSupport();
#endif

```

The following symbols are defined for use in cross-platform compilation: `WINDOWS`, `XBOX or XBOX360` and `WINDOWS_PHONE`. See Cross-Platform Conditional Compilation Symbols for further information.
> 2 votes

---
Tags: xna-4.0
---


title: Animate multiple entities

text:
# Question
Title: Animate multiple entities
I'm trying to animate multiple(3) entities using one model(IQM format).

It's working but performance is really bad because I'm calling `animate` function for each entity in my game loop (I think problem is there).

What's the best way to animate multiple entities (with different animation ofc) in OpenGL? I think I can try build one VBO / entity for better performances but I don't think it's the best way to do it.

# Answer
> 1 votes
You can do skinning using shaders in OpenGL. The IQM format is designed with this in mind. Upload the skinning matrices to a uniform and use the blend index and blend weight vertex arrays in the shader to do the skinning.

That way you only have to update the array of skinning matrices per entity you want to animate.

```
uniform mat4 SkinMatrix[256];
in vec4 att_BlendIndex;
in vec4 att_BlendWeight;

main() {
    vec4 p = vec4(0);
    p += SkinMatrix[int(att_BlendIndex.x)] * gl_Vertex * att_BlendWeight.x;
    p += SkinMatrix[int(att_BlendIndex.y)] * gl_Vertex * att_BlendWeight.y;
    p += SkinMatrix[int(att_BlendIndex.z)] * gl_Vertex * att_BlendWeight.z;
    p += SkinMatrix[int(att_BlendIndex.w)] * gl_Vertex * att_BlendWeight.w;
    gl_Position = gl_ModelViewProjectionMatrix * p;
}

```

---
Tags: opengl, animation, performance
---


# Question
Title: What files and libraries do I need for OpenGL and controls
I am starting a 3D game, however I find OpenGL file system very confusing. OpenGL package doesn't have one file, other package doesn't have another, so I need a summary of what files do I need to start playing with 3D. It would be good if it included keyboard and mouse controls.

Shortened question: Where can I get all files for OpenGl 4.0 and integrated controls libary?

# Answer
OpenGL comes as standard with the windows development environments (both visual studio and msys/mingw). What you want are two other components to help you get started with OpenGL 4.0: an extension loader library, and a simple toolkit to set up a window and get events.

Use glew or gl3w for the former, and freeglut or glfw for the latter.
> 1 votes

---
Tags: opengl
---