title: Jump handling and gravity

text:
# Question
Title: Jump handling and gravity
I'm new to game development and am looking for some help on improving my jump handling for a simple side scrolling game I've made. I would like to make the jump last longer if the key is held down for the full length of the jump, otherwise if the key is tapped, make the jump not as long. Currently, how I'm handling the jumping is the following:

```
Player.prototype.jump = function () {
    // Player pressed jump key
    if (this.isJumping === true)
    {
        // Set sprite to jump state
        this.settings.slice = 250;

        if (this.isFalling === true)
        {
            // Player let go of jump key, increase rate of fall
            this.settings.y -= this.velocity;
            this.velocity -= this.settings.gravity * 2;
        }
        else
        {
            // Player is holding down jump key
            this.settings.y -= this.velocity;
            this.velocity -= this.settings.gravity;
        }

    }

    if (this.settings.y >= 240)
    {
        // Player is on the ground
        this.isJumping = false;
        this.isFalling = false;
        this.velocity = this.settings.maxVelocity;
        this.settings.y = 240;
    }
}

```

I'm setting isJumping on keydown and isFalling on keyup. While it works okay for simple use, I'm looking for a better way handle jumping and gravity. It's a bit buggy if the gravity is increased (which is why I had to put the last y setting in the last if condition in there) on keyup, so I'd like to know a better way to do it. Where are some resources I could look at that would help me better understand how to handle jumping and gravity? What's a better approach to handling this? Like I said, I'm new to game development so I could be doing it completely wrong. Any help would be appreciated.

# Answer
Here's how I would suggest handling it:

First, have your `Player` class store a variable, `jumpForce`, which is a 2D-vector similar to `velocity` and `gravity`. Now, also have a constant, `initialJumpForce`, which is the immediate force that will be exerted on your player when the jump key is first pressed. When the jump key is pressed, and the player is grounded (e.g. `Player.settings.y` is `240`), then:

```
jumpForce = initialJumpForce;

```

And, each update:

```
// Calculate the net force acting on the player.
var netForce = this.jumpForce - this.settings.gravity;
this.velocity += netForce * deltaTime;

// Deteriorate the jumping force.
this.jumpForce -= this.settings.gravity;
// Do something to ensure that jumpForce doesn't become negative.

```

Note that an extra variable, `deltaTime`, appeared. This is something you must use when integrating velocity and position in an update loop. `deltaTime` will be the amount of time, in seconds, that has passed since the last frame.

Whenever the jump key is released, immediately set `Player.jumpForce` back to `0`. This way, gravity takes over entirely on your player. Essentially, holding down the jump key keeps the slowly diminishing jumping force alive to act upon your player while in the air.

You might also consider applying an impulse, or direct change in velocity when the jump key is pressed. While `jumpForce` will get the dynamics you want with jump controls, it will take time to act upon the player, making jumping appear sluggish. So, in addition to setting jump force, you could do something simple like:

```
this.velocity.y = 50;

```

I picked `50` arbitrarily... not sure what units you're using, but it's a value you can play with; same with `initialJumpForce`. Hope this helps :)
> 7 votes

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


# Question
Title: Farseer Physics Samples and Krypton how to reference game
I'm sure this is totally simple and yes I am new at this.

I am trying to set up Krypton inside farseer.
1. create a new Krypton engine in my sub screen aka AdvancedDemo1 : PhysicsGameScreen, IDemoScreen Via this.krypton = new KryptonEngine(this, "KryptonEffect"); The problem is the KryptonEngine(this wants reference to Game game, I cant seem to reference it from FarseerPhysicsGame : Game So how would I do that?

or 2. I can put it directly in FarsserPhysicsGame but again I cant seem to figure out how to reference FarseerPhysicsGame in AdvancedDemo1.

or 3. I can put it inside the public FarseerPhysicsGame() and do Componenets.Add(krypton) \[which works\] HOWEVER I cant figure out how to reference the compoenet once it is added.

You should be able to stop reading here , but for more detail I simply took the Farseer XNA Samples went into FarseerPhysicsGame.cs and deleted all the screens and menus except AdvancedDemo1 so there is one option and I just click that to load into the advancedDemo1 and thats where I want to put the lights from krypton.

Thanks.

Edit: Figured out 1 solution though I am still curious about others. Solution 1 I was able to use ScreenManager.Game(not sure why it was there but Ill try to figure it out later)

# Answer
> 1 votes
Well, the way I would do this is just have the two solutions imported alongside the main solution and then have the main solution reference each one. Then you can play with both Krypton and Farseer in your solution.

Then you can pass your Microsoft.Xna.Framework.Game class to whatever function you want.

I'm not quite sure exactly what you wish to do, but if it's just wanting to be able to use both libraries/solutions from within your solution, you don't need to do much more than import both solutions and then reference them. (Right click on your solution at the very top, then add reference)

If it's something else, please disregard the preceding.

---
Tags: xna, farseer-physics-engine
---


title: Dynamic Terrain Texture

text:
# Question
Title: Dynamic Terrain Texture
I've been looking at a 2D physics game called 'Hill Climb Racing' (Android and iOS) and was wondering how they went about texturing the terrain?

I've had a think about it and I've come up with nothing and finding a resource on the web has proved impossible. Please help.

The game mentioned uses Cocos2d. Would it be just as doable in a different environment?

**EDIT:**

I was looking at another question: Drawing large 2D sidescroller level terrain

The end result is what I'm looking for, but in my mind I was thinking that there would be some way to add this effect (using small textures) to some terrain specified by vertices rather than making a very large image to match whatever is seen in the level.

# Answer
You can accomplish this with UV mapping. Most likely they generated 2 "layers" of geometry. One for the grass, and one for the dirt.

The "dirt" strip lies below and has texture-coordinates that accumulate horizontally. As long as the dirt texture is tileable, it will nicely repeat. The goal here is to have no distortion.

For the "grass layer", I would create another strip of triangles that follows the curve of the landscape. There you can use a small texture (including shadow) and map the texture directly to each quad.

Here's an illustration:

The **Strip 2** is the dirt and **Strip 1** is the grass. As you can see a small grass-texture will be mapped to each quad of **Strip 1**, whereas the texture coordinates of **Strip 2** just add up and generate tiling (you can see the approximate horizontal texture coordinates below).
> 6 votes

# Answer
There are probably better solutions, but here's how I would do it:

1. Create two fairly large textures: one for the grass, one for the ground below. These textures should be roughly as large as the screen, or larger if the game engine and the hardware allow it. The texture should also look seamless when tiled.
2. As you generate the level (the curve of the grass), you should also generate two masks: one for the band of grass (mask A), and one for the ground (mask B).
3. Your final screen will look like this:

* background (sky)
    * ground, clipped with mask B
    * grass band, clipped with mask A
> 0 votes

---
Tags: 2d, textures, terrain, terrain-rendering
---


# Question
Title: What is the order-less rendering technique that allows partial transparency?
I've seen somewhere rendering technique that allows order-less rendering of partially transparent sprites/objects.

Though I can't remember what the technique is called, so I'm having trouble Googling it.

# Answer
There are lots of ways to achieve order-independent transparency.

The first (and I think oldest) type of algorithm is called depth peeling and works by "peeling" one transparency layer per pass (in the most basic version). This Nvidia paper for Dual Depth Peeling shows peeling two layers at the same time.

The second type which I only know as "order-independent transparency" (or OIT) works by storing transparent fragments during rendering (e.g. in a linked list) and then sorting them via compute shader. An example is contained in the DirectX 11 SDK, another (and lots of links) is here.

The next thing I remember is Order Independent Translucency which stores fragments by hijacking MSAA.

And last but not least there is a sample for Stochastic Transparency in the latest NVIDIA Graphics SDK 11 Direct3D

Hope this contains the algorithm you searched for.
> 13 votes

# Answer
Jens covered the different ways pretty well. I would like to add that additive blending is also order independent and it can be used in limited use cases to achieve pretty good results with very little programming effort.

The following image is rendered with a color something like (-0.5, 1.0, -0.5) with additive blending. Positive color values are given for one color channel and negative values for the other two channels to not increase the average brightness.
> 11 votes

---
Tags: opengl, rendering, transparency
---


# Question
Title: Maximum number of controllers Unity3D can handle
I've been trying to find out the maximum amount of xbox controller Unity3D can handle on one editor. I know through networking, Unity is capable of having as many people as your hardware can handle. But I want to avoid networking as much as possible.

Thus, on a single computer, and in a single screen (think Bomberman and Super Smash Brothers) how many xbox controllers can Unity3D support?

I have done work in XNA and remember that only being capable of support 4, but for the life of me, I can't find any information that tells me how many Unity can support.

# Answer
Turns out, the answer is 11 different controllers Unity can handle straight out of the box. If you wish to add more, you need to write your own plug in.
> 1 votes

---
Tags: unity, input, xbox-controller
---


title: Absorbtion 2d image effect

text:
# Question
Title: Absorbtion 2d image effect
I want to create a specyfic 2d image effect. It consists in modifying a sprite so it looks like it is being zoomed to a point or "absorbed" by that point. I'm not really sure what is the technical name of this effect so I cannot explain it correctly.

Here you can see a video of what I'm talking about, it is the effect when the character absorbs the three glyphs.

http://www.youtube.com/watch?v=PIo-GddsMcU&t=4m45s

What is the name of this effect? How can I implement it with XNA for 2D textures/sprites?

# Answer
> 1 votes
You could call it texture warping, or simply texture deformation. In XNA you could achieve something like that by transforming the texture's pixels' coordinates. You map the pixels of the texture to a grid, then modify the positions of the grid's vertices. Since the effect in Castlevania is quite unique, you will have to experiment and play around with your own deformation algorithm until you achieve an effect you like.

There's a nice tutorial for a similar technique here: Screen-space deformations in XNA

---
Tags: xna, 2d, image, graphic-effects
---


# Question
Title: trapped inside a Graph : Find paths along edges that do not cross any edges
This is a graph based platformer level and the round shapes are creatures.

I am looking for a path traveling along edges that does not cross other edges(To simulate the creature crawling on the floors and walls).

Here is what the correct path would look like:

# Answer
When traversing the graph, always turn the same direction. You can use cross product to check what is the left or rightmost direction in a junction.
> 8 votes

---
Tags: algorithm, path-finding, geometry, graph
---


# Question
Title: How do I calculate opposite of a vector, add some slack
How can i calulate a valid range (RED) for my object's (BLACK) traveling direction (GREEN). The green is a Vector2 where x and y range is -1 to 1.

What I'm trying to do here is to create rocket fuel burn effekt. So what i got is

* rocket speed (float)
* rocket direction (Vector2 x = \[-1, 1\], y = \[-1, 1\])

I may think that rocket speed does not matter as fuel burn effect (particle) is created on position with its own speed.

# Answer
You need a normal vector for your rocket direction. You can use cross product to calculate it, which in 2D results to `normal = vector(direction.y, -direction.x);`

Now the burn vector is just a normalized linear combination of -direction and normal. E.g.

```
float k = random() * 0.3;
burn = normalize(normal * k - direction * (1 - k));

```
> 2 votes

# Answer
I'd suggest you calculate the polar angle (angle with the X axis) of the vector. Then you can rotate it by 180° and for each particle add a randomized value based on the width of the burn effect cone (e.g. +/- 30°). Then convert the angle back to vector.

Here's some C# example code to add a PolarAngle property to a Vector2D class. Note that it's operating in Radian not Degree.

```
/**
 * An angle describing the orientation of the Vector. (-1,0) is 0. (1,0) is Pi.
 */
public double PolarAngle
{
    get
    {
        return Math.Atan2(Y, X) + Math.PI;
    }

    set
    {
        double len = Length;
        X = len * Math.Cos(value);
        Y = len * Math.Sin(value);
    }
}

```
> 0 votes

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


title: Optimal way to learn DirectX?

text:
# Question
Title: Optimal way to learn DirectX?
I am finding it very difficult to learn DirectX 11. The MSDN website is just full of unorganized information that doesn't seem to help at all. I am particularly looking for something that explains many if not all aspects of developing with DirectX 11. I have been searching for weeks and still come up empty. I have found some books but they don't really explain the fundamentals of the language at all. Thanks in advanced.

# Answer
> 2 votes
There is a series of DirectX 11 C++ tutorials here.

I've found that this site isn't too bad. I don't particularly like his programming style, but I suppose that's not really the point of his site.

# Answer
> 1 votes
this dude dose it pretty good, exept that he wants cash for some topcis. http://directxtutorial.com/

but the basics and fundementals are free. he explains pretty good aswell. there is some chapers on transformation, memory managment and directx stuff there. a good read!

---
Tags: directx, software-engineering
---


title: coordinate transformation

text:
# Question
Title: coordinate transformation
I have two coordinate systems, like so

How can I transform a point on the one of the coordinate system to other ?

Pxyz = M . Px'y'z' what is M ?

# Answer
From the image it looks like both your coordinate systems are cartesian coordinates, where the only difference between the two is that one has a different origin from the other.

If this is the case then to translate from `xyz` coordinates to `x'y'z'` coordinates all you need is a translation, i.e.

```
x' = x + dx
y' = y + dy
z' = z + dz

```

Where \[dx, dy, dz\] is the difference between the origins of the two coordinate systems.

Matrix multiplications always have the origin as a fixed point and so you can't perform translations using a 3x3 matrix, however as a sort of workaround you can express your 3-dimensional coordinates as the 4-dimensional vector `[x, y, z, 1]` and use a 4x4 transformation matrix that includes a translation, e.g.

```
|1 0 0 dx | |x|   |x + dx|
|0 1 0 dy | |y|   |y + dy|
|0 0 1 dz | |z| = |z + dz|
|0 0 0 1  | |1|   |   1  |

```

You can then ignore the 4th component to get the translated 3D coordinates. See more on Wikipedia here
> 6 votes

---
Tags: matrix, transformation
---


title: Making a perfect map (not tile-based)

text:
# Question
Title: Making a perfect map (not tile-based)
I would like to make a map system as in the GameMaker and the latest code is here. I've searched a lot in google and all of them resulted in tutorials about tile-maps. As tile maps do not fit for every type of game and GameMaker uses tiles for a different purpose, I want to make a "Sprite Based" map.

The major problem I had experienced was collision detection being slow for large maps. So I wrote a QuadTree class here and the collision detection is fine upto 50000 objects in the map without PixelPerfect collision detection and 30000 objects with PixelPerferct collisions enabled.

Now I need to implement the method "isObjectCollisionFree(float x, float y, boolean solid, GObject obj)". The existing implementation is becoming slow in Platformer games and I need suggestions on improvement.

The current Implementation:

```
/**
 * Checks if a specific position is collision free in the map.
 *
 * @param x The x-position of the object
 * @param y The y-position of the object
 * @param solid Whether to check only for solid object
 * @param object The object ( used for width and height )
 * @return True if no-collision and false if it collides.
 */
public static boolean isObjectCollisionFree(float x, float y, boolean solid, GObject object){
    boolean bool = true;
    Rectangle bounds = new Rectangle(Math.round(x), Math.round(y), object.getWidth(), object.getHeight());
    ArrayList<GObject> collidables = quad.retrieve(bounds);
    for (int i=0; i<collidables.size(); i++){
        GObject obj = collidables.get(i);
        if (obj.isSolid()==solid && obj != object){
            if (obj.isAlive()){
                if (bounds.intersects(obj.getBounds())){
                    bool = false;
                    if (Global.USE_PIXELPERFECT_COLLISION){
                        bool = !GUtil.isPixelPerfectCollision(x, y, object.getAnimation().getBufferedImage(), obj.getX(), obj.getY(), obj.getAnimation().getBufferedImage());
                    }
                break;
                }
            }
        }
    }
    return bool;
}

```

Also some tutorials on `sprite-based` maps are needed. But on google search, I get tile based maps.

My question is how can I make a more efficient map system? I don't want using tile-maps as they aren't fit for every game.

And since the solid objects won't move, should I consider them as tiles??

Thanks.

# Answer
For collision detection doom used a technique called a blockmap instead of a quadtree, to find objects that needed to be tested for collisions.
> 0 votes

---
Tags: collision-detection, maps
---


# Question
Title: How can I reflect a point with respect to the plane?
How can I reflect a point with respect to a plane?

Example:

I have three points (0,0,2), (4,0,0) and (0,8,0). And I have a point (x,y,z). From these, I want derive a composite transformation matrix. How can I do that?

# Answer
Given the following:

The calculation steps for the augmented reflection matrix are as follows:

1) Calculate the 3x3 reflection matrix **R0** for a plane with the same normal vector, but which lies at the origin

**Ro** = **I** \- 2 **NNT**

2) Augment the reflection matrix to create the augmented reflection matrix **RA**

3) Calculate the final augmented reflection matrix by first applying the translation **A**, mirroring the point by **RA**, then applying the reverse of the translation **A-1**

**R** = **ARAA-1**
> 5 votes

# Answer
Three points, **A**, **B** and **C** define a plane. The lines **AB** and **AC** are both on the plane, so their normalised cross product, perpendicular to both lines, is the plane's normal **n**:

**n** = normalise( (**B** \- **A**) ⨯ (**C** \- **A**) )

The equation for the plane is given by: **n** · **x** \+ d = 0, where -d is the displacement between the plane and the origin in the normal direction, i.e.: d = -**n** · **A**.

An arbitrary point **x** can be described as the sum of two vectors, **u** pointing from plane to point in the normal direction, **v** being the other component:

**u** = (**x** · **n** \+ d) **n**

**v** = **x** \- **u**

The mirror image of **x** can then be calculated by flipping the **u**-component: **x'** = -**u** \+ **v**. Now that **x'** is known, capturing the calculation in a transformation matrix is trivial: solve **T x** = **x'** for **T**.
> 4 votes

---
Tags: matrix, transformation
---


title: Amazon GameCircle Integration

text:
# Question
Title: Amazon GameCircle Integration
I'm trying to integrate Amazon GameCircle and I have been able to successfully initialize GameCircle in my app, but the problem is when I click on the button that displays achievements, the GameCircle achievement list comes up but it says "You have unlocked 0 of 0 achievements". Same happens with leaderboards i.e there are no leaderboards for this app. I have created a Leaderboard and a few achievements on the online developer portal for Amazon but they don't show for some reason. Can someone help me with this. Any links/resources that help with integrating GameCircle will be appreciated.

Thanks.

# Answer
I had the same problem. To solve it follow these steps:

1. Go to your Amazon Developer Portal (https://developer.amazon.com)
2. Go to "MyApps"
3. Hover your mouse over the settings icon on the right of the app in question and go to your GameCircle settings (also known as Game Services)
4. Click "Sandbox"
5. Enter the name of the Amazon GameCircle profile that you are using to test your application

That should be it! It only takes a few moments to update so next time you open your app you should see both the leaderboards and the achievements.
> 1 votes

---
Tags: android
---


# Question
Title: how to change the number of rendered frames in Blender
i´m using blender to render an animation in single pictures and i want to make an 16 frames animation out of an 24 frames one without changing the set keyframes. Is there an option to skip every 3rd frame and just render the rest? I only found the frame step option, which allows you to render every 3rd, but not 2 frames and skip the 3rd. If anyone could help, thank you very much!

# Answer
Using the DopeSheet panel, select all the key frames that make up your 24 frames of animation. Then press `s` to enter scale mode. Scale the 24 frame animation to 16 frames.
> 2 votes

---
Tags: animation, rendering, blender
---


# Question
Title: Rotate an object given only by its points?
I was recently writing a simple 3D maze FPP game. Once I was done fiddling with planes in OpenGL, I wanted to add support for importing Blender objects. The approach I used was triangulization of the object, then using Three.js to export the points to plaintext and then parsing the result JSON in my app.

The example file can be seen here: https://github.com/d33tah/tinyfpp/blob/master/Data/Models/cross.txt The numbers represent x,y,z,u,v of a single vertex, which combined in three make a triangle.

Then I rendered such an object triangle-by-triangle and played with it. I could move it back and forth and sideways, but I still have no idea how to rotate it by some axis. Let's say I'd like to rotate all the points by five degrees to the left, how would a code doing it look like?

# Answer
I think the easiest way to rotate a vertex around an axis is using the Rodrigues Rotation Formula.

Here is my implementation of it using C++ and the library GLM:

(Note: it may not be the most efficient way, but I use it for learning purpose :3. Also, I'm using row major order (not the way GLM do things), so the multiplication is inverse later. Also, rotation are counter-clockwise :3)

```
glm::mat3 rodriguesMatrix(const double degrees, const glm::vec3& axis) {
glm::mat3 v = glm::mat3(
    axis.x*axis.x, axis.x*axis.y, axis.x*axis.z,
    axis.x*axis.y, axis.y*axis.y, axis.y*axis.z,
    axis.x*axis.z, axis.y*axis.z, axis.z*axis.z
    );

glm::mat3 v2 = glm::mat3(
    0, -axis.z, axis.y,
    axis.z, 0, -axis.x,
    -axis.y, axis.x, 0
    );

glm::mat3 rotation = cos(degrees * M_PI/180.f) * glm::mat3(1.0f) + (1-cos(degrees * M_PI/180.f)) * v + sin(degrees * M_PI/180.f) * v2;

return rotation;
}

```

So, let's say you want to rotate the vertice `(3.866185 -0.996761 -1.366355)`(first of your example) by `5 degress` along the `y` axis. You can do it by doing something like:

```
glm::vec3 y_unit = glm::vec3(0, 1.f, 0);

glm::mat3 rotationMatrix = rodriguesMatrix(5, y_unit);

glm::vec3 myVertice = glm::vec3(3.866185,-0.996761,-1.366355);

glm::vec3 myVerticeRotated = myVertice*rotationMatrix;

```
> 2 votes

# Answer
```
glPushMatrix();

// Translate our object in  (x,y,z) position
glTranslatef(x, y, z);

// Rotates the object around a rotation axis
// i.e. glRotatef(45.0, 0.0, 1.0, 0.0) rotates 45 degrees around the y-axis
glRotatef(angle, rot_axis_x, rot_axis_y, rot_axis_z);

// Create a function for drawing the object
Draw();

glPopMatrix();

```

---

You need to draw you're object preferably in the origin, because every rotation that you apply will be done around a position vector (vector that starts from the origin), and than you can translate it. OpenGl will first rotate your object and then it will translate it, so it will call the functions in reverse order. If you change the order, you will first translate the object and then rotate it around the position vector.
> 5 votes

---
Tags: opengl, geometry
---


title: IrrKlang with Ogre

text:
# Question
Title: IrrKlang with Ogre
I'm trying to set up sound in my Ogre3D project. I have installed irrKlang 1.4.0 and added it's include and lib directories to my projects VC++ Include and Library directories, but I'm still getting a Linker error when I attempt to build. Any suggestions?

```
(Error 4007 error LNK2019: unresolved external symbol "__declspec(dllimport) class irrklang::ISoundEngine * __cdecl irrklang::createIrrKlangDevice(enum irrklang::E_SOUND_OUTPUT_DRIVER,int,char const *,char const *)" (_imp?createIrrKlangDevice@irrklang@@YAPAVISoundEngine@1@W4E_SOUND_OUTPUT_DRIVER@1@HPBD1@Z) referenced in function "public: __thiscall SoundManager::SoundManager(void)" (??0SoundManager@@QAE@XZ)

```

# Answer
Okay, after looking at this for awhile it seems I was making two mistakes:

1. The lib directory for irrKlang is divided in two, so instead of adding `(IRRKLANGDIRECTORY)\lib` to my library directories, I should have been using `(IRRKLANGDIRECTORY)\lib\Win32-visualStudio`.
2. Including the lib directory wasn't sufficient, I also needed to specify the use of the irrklang library file at the top of my class `#pragma comment(lib, "irrklang.lib")`.
> 0 votes

---
Tags: ogre, sound, audio
---


title: Confusing Callbacks

text:
# Question
Title: Confusing Callbacks
I'm trying to programm now a "game", and started with the EmptyProject that's provided by the DirectX SDK. The problem is that the Callbacks are confusing me. Can please someone explain me?

Edit:

```
DXUTSetCallbackD3D9DeviceAcceptable( IsD3D9DeviceAcceptable ); // not sure but I think       that's the caps?
DXUTSetCallbackD3D9DeviceLost( OnD3D9LostDevice );
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCallbackFrameMove( OnFrameMove );

```

# Answer
> 0 votes
The DXUT Framework requires you to define a number of functions in order to plug into it. Each of those names - IsD3D9DeviceAcceptable, OnD3D9LostDevice, ModifyDeviceSettings, and OnFrameMove - are functions that YOU need to define in your code. The signatures are as follows:

```
static bool CALLBACK IsD3D9DeviceAcceptable( D3DCAPS9* PCAPS, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void *pUserContext);

static void CALLBACK OnD3D9LostDevice( void* pUserContext );

static bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );

static void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );

```

So in the first function you determine if the d3d9 device will work for your program or not, and return true if it does. In the second you tell it what to do if it loses the device (if someone minimizes the screen for instance). In the third you allow the user to change the device settings, and.... I'm actually not too sure about the fourth, I use DXUTOnFrameRender instead.

It's annoying that Microsoft took down the documentation for the DXUT library. If you Google any of those function names you'll find the Japanese version of MSDN, which somehow survived the purge. If you really want a complete example of the DXUT library in use, try the Game Coding Complete code:

http://code.google.com/p/gamecode4/

The file GameCode4.cpp is the initializer, where they use these function declarations just like you typed them in. The bodies of the user-defined functions are in gamecode.cpp and gamecode.h

I believe the DXUT tutorials are also in the DirectX SDK for DX9

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


# Question
Title: How handle Nifty initialization in a Slick2D state based game?
I'm using Slick2D and Nifty GUI. I decided to use a state based approach for my game and since I want to use Nifty GUI, I use the classes `NiftyStateBasedGame` for the main and `NiftyOverlayBasicGameState` for the states.

As the description say, I'm suppose to initialize the GUI in the method `initGameAndGUI` on my states, no problem:

```
@Override
protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException {
    initNifty(gc, sbg)
}

```

It works great when I have only one state but if I'm doing a call to `initNifty` several times from different states, it will raise the following exception:

```
org.bushe.swing.event.EventServiceExistsException: An event service by the name NiftyEventBusalready exists.  Perhaps multiple threads tried to create a service about the same time?
at org.bushe.swing.event.EventServiceLocator.setEventService(EventServiceLocator.java:123)
at de.lessvoid.nifty.Nifty.initalizeEventBus(Nifty.java:221)
at de.lessvoid.nifty.Nifty.initialize(Nifty.java:201)
at de.lessvoid.nifty.Nifty.<init>(Nifty.java:142)
at de.lessvoid.nifty.slick2d.NiftyCarrier.initNifty(NiftyCarrier.java:94)
at de.lessvoid.nifty.slick2d.NiftyOverlayBasicGameState.initNifty(NiftyOverlayBasicGameState.java:332)
at de.lessvoid.nifty.slick2d.NiftyOverlayBasicGameState.initNifty(NiftyOverlayBasicGameState.java:299)
at de.lessvoid.nifty.slick2d.NiftyOverlayBasicGameState.initNifty(NiftyOverlayBasicGameState.java:280)
at de.lessvoid.nifty.slick2d.NiftyOverlayBasicGameState.initNifty(NiftyOverlayBasicGameState.java:264)

```

The `initializeEventBus` that raises the exception is called from the `Nifty` constructor and a new `Nifty` object is created within the `initNifty` method:

```
public void initNifty(
    final SlickRenderDevice renderDevice,
    final SlickSoundDevice soundDevice,
    final SlickInputSystem inputSystem,
    final TimeProvider timeProvider) {
    if (isInitialized()) {
       throw new IllegalStateException("The Nifty-GUI was already initialized. Its     illegal to do so twice.");
    }

    final InputSystem activeInputSystem;
    if (relayInputSystem == null) {
       activeInputSystem = inputSystem;
    } else {
      activeInputSystem = relayInputSystem;
      relayInputSystem.setTargetInputSystem(inputSystem);
    }

    nifty = new Nifty(renderDevice, soundDevice, activeInputSystem, timeProvider);
  }

```

Is this a bug in the Nifty for Slick2D implementation or am I missing something? How am I supposed to handle Nifty initialization over multiple states?

# Answer
> -1 votes
I am not familiar with the Nifty GUI, so take this advice with a grain of salt, but I would suggest trying to determine if you really need to initialize the GUI multiple times. It might be better to simply initialize once, and use other methods to make the changes you need when you change states.

If this is the case, you can either store a boolean value to track whether you have initialized the GUI already, and check this before calling `initNifty`. If you have already initialized it, simply skip the initialization call.

---
Tags: java, slick, nifty-gui
---


title: 2D Collision detection for Pinball Game

text:
# Question
Title: 2D Collision detection for Pinball Game
So far in previous games I have used simple 2D collision with boxes then checking at pixel level for a collision.

If making a pinball game in nearly a lot of frames the ball will be in contact with a wall or another surface so is there another approach?

# Answer
Back in the days (1990), old pinball games were made like this :

There is several layers for playfield (what you see when playing the game) :

and several layers for collisions :

The left grayscale picture is a collision map for main game, right picture is a collision map for special area : pinball ramps.

`White` = free area for ball, color index there is 255.

`Gray` = ball will be "pushed away" from this zone. color index = angle of vector to add to ball position. light gray = 0 deg. dark gray = 360 deg.

Some pseudo code :

```
void do_ball_physics()
{
    while(1)
    {
         byte color = read_pixel_under_ball(ballx, bally); //one pixel read
         if(color == 255) //see remark below
            break;
         float vectorx = sin(color/255.0f * 2.0f * PI);
         float vectory = cos(color/255.0f * 2.0f * PI);
         ballx += vectorx; //push ball away from one unit
         bally += vectory; //

    }
}

```

Some special color indexes can also be used for something else than collision, a custom color range (eg : 240 - 255) can be reserved for detecting special zones like `spinners`, `triggers`, `bumpers`, `holes`, ...

As you can see, this is very simple. There is only a few pixels "read" per frame. Because of this you can make the physics simulation run at a real high framerate eg : 200 fps. Using high framerate will smooth simulation and reduce "tunneling" (this happen when ball goes too fast and pass trough elements without colliding). That simplicity is also what make smooth pinball games possible on `386 computers` (and even fast `286`) back in the days (among some other tricks like color cycling, vga scrolling and sprite masking ...).

Today, most pinball games are no more made like this. Instead the playfield is a 2d/3d scene using polygons or sprites and collisions are made against some simplified lines, bezier curves, or spheres representing a simplified shape of visual playfield.

example (from visual pinball) :

Some game companies use their own physics engine but another, easier way is to use a physics engine like `Box2D` or `Bullet`. Most iPhone pinball games i saw were using a pre-existing physics engine + some 3d assets.
> 21 votes

# Answer
Pinballs have very rich sets of physics, not only holes or walls, but also reacting elements (hitting back) or uneven surface where the ball slows down and then gets it's speed back.

If you want to create a good pinball, the way to go is either to use a 3D collision detection, or self-tailored system with every collidable object having a method with distance and velocities parameters, returning changed velocities.
> 2 votes

# Answer
I made a pinball game a while ago; it was pixel based as well. I had a collision map which just contained the collision data. An approximate collision normal was easy to find:

Take the area of collision map overlapping the ball, find the centre, form the vector from that point to the ball centre, then normalise.

Hope that gives you some ideas :)
> 2 votes

# Answer
First if you make a pinball game, you'll most likely need more bounding-CIRCLE-collision-detection than the bounding BOX one :-)
Given the complexity of the physic involved in a full fledged pinball, i would suggest to look on an existing 2D physic engine. Box2D has quite a reputation in javascript, there might be others but i didn't encounter any good (and free) one.
Rq1 : You certainly use (as i do) the classical split in your game between update and draw. And you use a timer (setInterval/setTimeout) and/or RequestAnimationFrame to call update, then draw, in a regular fashion. A pinball might be the type of game where you want to have one timer driving update, and another driving the draw, so you can adjust the rate of each independently, to work on a wide range of devices. Because you can't just drop (update+draw) if the device is too slow : if the time between two updates (dt) becomes too long, the physic engine might miss a collision.
> 1 votes

# Answer
You might take a look at visual pinball vs future pinball for the 2d vs 3d subject. If you play visual pinball (Everything is made in 2d) then play future pinball, or something like Zen Pinball you do feel the difference in how they play. I personally prefer the 3d, but your project may be better suited to 2d, Only you would be able to decide that
> 0 votes

---
Tags: 2d, collision-detection, javascript
---


# Question
Title: Splitting Graph into distinct polygons in O(E) complexity
If you have seen my last question: trapped inside a Graph : Find paths along edges that do not cross any edges

How do you split an entire graph into distinct shapes 'trapped' inside the graph(like the ones described in my last question) with good complexity?

Please note each vertex has a fixed x,y position.

What I am doing now is iterating over all edges and then starting to traverse while always taking the rightmost turn. This does split the graph into distinct shapes. Then I eliminate all the excess shapes (that are repeats of previous shapes) and return the result.

The complexity of this algorithm is O(E2). I am wondering if I could do it in O(E) by removing edges I already traversed previously. My current implementation of that returns unexpected results.

# Answer
The following simple algorithm should give you O(E) solution:

1. Create a directed graph from your graph by adding arcs to both directions for each edge in your initial graph
2. Start traversing the graph from any node with the current logic of always turning to the same direction in junctions
3. Only proceed through arcs that are directed away from the node
4. Remove the arc after traversing it
5. Remove the node if it has zero connections left
6. When you reach the starting node, you have found a polygon
7. Repeat from 2. until no nodes are left
> 1 votes

# Answer
After some trial and error I found a solution.

1. Iterate over all edges, one by one.
2. Starts a path from each edge in it's turn, saving the shape as you go, taking the rightmost turn in each vertex.
3. After traversing three edges, check if any previous shape uses these three edges\*.
4. If not continue to traverse until you reach the starting point and save the loop.

* To check if a previous path used three edges, create a list of arrays of paths. The list is indexed from 0 .. (E - 1) where E is the # of edges. The array at index i in the list contains all the paths that use edge i.
> 0 votes

---
Tags: geometry, graph
---


title: Load SpriteFont in XNA

text:
# Question
Title: Load SpriteFont in XNA
I'm planning on my game using multiple backgrounds so I'm trying to use spritefonts to draw the text. Every time I load my spritefont I get a error.

```
Line1 = content.Load<SpriteFont>("Courier New");
Line2 = content.Load<SpriteFont>("Courier New");

```

This is the error I get.

Error loading "Courier New". File not found.

Although this was the font listed on the official microsoft website http://msdn.microsoft.com/en-us/library/bb447673.aspx.

# Answer
> 7 votes
You have to add new a new SpriteFont item to your content project. Inside the .spritefont file, there is FontName element. Replace the default value with Courier New.

Take note of the asset name of the .spritefont file you added. Because that is the name you should reference inside your game. Assuming you named the asset as courier, you could load the font like this

```
SpriteFont Line1 = content.Load<SpriteFont>("courier");

```

# Answer
> 3 votes
You can only load content that's in your Content project. Since there isn't any file with the name "Courier New" (.ttf, or whatever) in your Content project, it's natural you'd get a *File not found* error.

You can't just load system fonts. The example in the official Microsoft website just needed an example font name. For their situation to work, they'd need a "Courier New.ttf" (or something) in the corresponding Content project.

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


# Question
Title: Alternatives to Component Based Architecture?
Usually when I develop a game I will use an architecture like what you see below. What other architectures are popular for simple game development? I'm concerned about having a narrow view of what exists out there for architectures beyond this. Is this an example of component-based architecture? Or is this something else? What would that look like? What alternatives exist?

```
public abstract class ComponentBase {

    protected final Collection<ComponentBase> subComponents = new LinkedList<ComponentBase>();

    private boolean enableInput;
    private boolean isVisible;

    protected ComponentBase(boolean enableInput, boolean isVisible) {
        this.enableInput = enableInput;
        this.isVisible = isVisible;
    }

   public void render(Graphics2D graphics) {
        for(ComponentBase gameComponent : this.subComponents) {
            if(gameComponent.isVisible()) {
                gameComponent.render(graphics);
            }
        }
    }

    public void input(InputData input) {
        for(ComponentBase gameComponent : this.subComponents) {
            if(gameComponent.inputIsEnabled()) {
                gameComponent.input(input);
            }
        }
    }

    ... getters/setters ...

    public void update(long elapsedTimeMillis) {
        for(ComponentBase gameComponent : this.subComponents) {
            gameComponent.update(elapsedTimeMillis);
        }
    }

}

```

# Answer
> Is this an example of component-based architecture? Or is this something else?

No this is a typical game object with multiple responsibilities. It handles everything and calling it component doesn't make it a component as in component based design.

> What would that look like?

A component based design? There are multiple questons with great answers already:

The component based architecture could look like this:

```
public abstract class ComponentBase {
    public abstract void update(long elapsedTimeMillis);
}

public class PositionComponent extends ComponentBase {
    float x;
    float y;
    float z;
    quaternion r;
}

public class MovementComponent extends ComponentBase {
    float x;
    float y;
    float z;
    quaternion r;

    public void update(long elapsedTimeMillis){
        /* update position component */
    }
}

public class RenderComponent extends ComponentBase {
    RenderModelStructure model;

    public void update(long elapsedTimeMillis){
        /* update the component's engine specifics
        rendering should be done in the render engine  */
    }
}

public class InputComponent extends ComponentBase {

    public void update(long elapsedTimeMillis){
        /* update impacted components */
    }

    public void input(InputData input) {
        /* does whatever input does */
    }
}

```

> What alternatives exist?

The chalkboard design where everything is available for everything to modify. Your approach based on heavy inheritance, and any mix of the different approaches.

There are games written with a very prohiminnent use of arrays, i.e.:

```
struct position { float x; float y; }
struct movement { float x; float y; }
struct enemy { position* p; movement* m; int shootTime; }
enemy[50] enemies;

```
> 5 votes

# Answer
A few methods (patterns? structures? styles?) I've used (excluding the popular version of component-based architecture) in *pseudocode*:

* Inheritance: `class Player extends Character`
* Composition: `class Player { Character baseChar; }`
* Composition with registration: `class NPC { Pathfinder P; NPC(){ InitAndRegisterPathfinder( ref P ); } }`
* Interface: `class Player { Renderable R; Player(){ R = CreateRenderable(); } }`
* Internal implementation of interface: `class Player extends Renderable { Player(){ RegisterRenderable( ref this ); } }`
* Quick & dirty composition: `class World { Vec3 playerPos; ... }` or even `function Game(){ Vec3 playerPos; while(true){...} }`

All of these have their uses. To dismiss any in favor of some imagined "supreme power of component-based architecture" would just mean that one day you'll wonder how the other guy made his game so quickly.
> 5 votes

# Answer
This will not be a full answer.

In my opinion there are no simple games. Every game is sophisticated in her own way.

This is not an example of component based architecture. This a polymorphic design. To be a component based design it need's components!

I am not very experienced in game development - but I can't see a better alternative.
> 1 votes

---
Tags: java, component-based
---


title: How do you turn a cube into a sphere?

text:
# Question
Title: How do you turn a cube into a sphere?
I'm trying to make a quad sphere based on an article, which shows results like this:

I can generate a cube correctly:

But when I convert all the points according to this formula (from the page linked above):

```
    x = x * sqrtf(1.0 - (y*y/2.0) - (z*z/2.0) + (y*y*z*z/3.0));
    y = y * sqrtf(1.0 - (z*z/2.0) - (x*x/2.0) + (z*z*x*x/3.0));
    z = z * sqrtf(1.0 - (x*x/2.0) - (y*y/2.0) + (x*x*y*y/3.0));

```

My sphere looks like this:

As you can see, the edges of the cube still poke out too far. The cube ranges from `-1` to `+1` on all axes, like the article says.

Any ideas what is wrong?

# Answer
You've miswritten the formula.

```
x = x * sqrtf(1.0 - (y*y/2.0) - (z*z/2.0) + (y*y*z*z/3.0));
y = y * sqrtf(1.0 - (z*z/2.0) - (x*x/2.0) + (z*z*x*x/3.0));
z = z * sqrtf(1.0 - (x*x/2.0) - (y*y/2.0) + (x*x*y*y/3.0));

```

You modify the original `x` and overwrite it. Then you modify `y` based not on the original `x` but the modified `x`. Then you modify `z` based on the modified version of *both* of those.

Preserve the originals, and calculate this:

```
float dx = x * sqrtf(1.0 - (y*y/2.0) - (z*z/2.0) + (y*y*z*z/3.0));
float dy = y * sqrtf(1.0 - (z*z/2.0) - (x*x/2.0) + (z*z*x*x/3.0));
float dz = z * sqrtf(1.0 - (x*x/2.0) - (y*y/2.0) + (x*x*y*y/3.0));

```

Use dx, dy and dz from then on.
> 28 votes

---
Tags: 3d, geometry, sphere
---


title: How to add text box in slick2d?

text:
# Question
Title: How to add text box in slick2d?
I wanted to let the player rename the character of my game. So I thought that making a text box and when he clicks the ok button, the text inside the text box will make it to a string and render it on the screen. How do I let the user type their own text?

# Answer
> 3 votes
You have reached the point where you need to use a GUI (for graphical user interface) in your game. Sometimes, in games, you will only need buttons or similar simple components. In this case, i would recommend doing it yourself, a button is something really simple to do.

Considering a button is a *clickable image*, using Slick2D, a button could be something like that:

```
class Button {

    //attributes...

    public Button(int x, int y, int width, int height, Image image, ActionHandler actionHandler) {
        buttonShape = new Rectangle(x, y, width, height)
    }

    //where x and y define the location of the mouse cursor
    public boolean checkClick(int x, int y) {
        return buttonShape.includes(x, y);
    }

    public render(Graphics g, ...) {
        g.drawImage(image, x, y);
        //other stuffs
    }
}

```

`ActionHandler` interface a way to pass user code to the button that would be executed when the button is clicked (see below):

```
public interface ActionHandler {

    public void onAction();
}

```

And then add a kind of listeners system that would listen for mouse events (look at the Slick2D API to learn about catching mouse events) and proceed the registered buttons to see if one of them was clicked.

Then a button could be defined like that:

```
Button b = new Button(x, y, width, height, new ActionHandler() {
    public void onAction() {
        System.out.println("CLICKED");
    });
GUIManager.registerButton(b);

```

And in your GUI logic:

```
public void checkForButtonInteractions(int mousex, int mousey) {
    for (Button b : GUIManager.getRegisteredButtons()) {
        if (b.checkClick(mousex, mousey)) {
            b.getActionHandler().onAction();
        }
    }
}

```

---

The above shows that you can easily implement *simple* GUI components without any external tools, a button or a check box for example. However, if you think you will need more complex components like textfields, combo box, panels, draggable windows etc. i highly recommend using an already existing GUI system and use it in your game.

As far as i know, with Slick2D, you have to major choices:

Both are made in Java using LWJGL and Slick2D implementations are available. For example, NiftyGUI provide a custom implementation of the `BasicGame`, `StateBasedGame`, `BasicGameState` that would natively handle low level Nifty stuffs such as initializing etc.

The choice of TWL or NiftyGUI is a subjective question, a lot of people on the Slick2D forums will recommend using TWL since it seems like the Slick2D support is a bit more mature than with Nifty. I personally use Nifty.

---

In conclusion, you will have set your requirements and then choose between doing it yourself or using an existing GUI system.

If you decide to create your own GUI system, Slick2D seems to provide some tools to help the process:

# Answer
> 0 votes
I haven't use slick2d but I know it's an engine based on lwjgl. It also seems to have a rudimentary GUI system. Searching through the API, I found the TextField class, which belongs to the gui package. You should search for tutorials about using the gui system in slick2d, though. I don't have enough experience to help you further.

---
Tags: java, gui, slick
---


title: Non-object-oriented game tutorials

text:
# Question
Title: Non-object-oriented game tutorials
I've been tasked with writing an essay extolling the virtues of object oriented programming and creating an accompanying game to demonstrate them.

My initial idea is to find a tutorial for a simple game written in a programming language which does not follow the OOP paradigm (or written in an OOP language but not in an OOP way) and recreate it in an OOP way using either C# or Java (haven't yet decided). This would then allow me to make concrete comparisons between the two.

The game doesn't have to be anything complex; Tetris, Pong, etc. that sort of thing. The problem I've had so far is finding a suitable tutorial, any suggestions?

# Answer
> 3 votes
You'll need something non-OOP to contrast with, which isn't just a bunch of spaghetti in which any clean or well structured code will be an improvement. Here are a few links to non-object oriented approaches that you can look at.

Functional programming in a few flavors:

Declarative or rule-based systems, like prolog or Inform 7 for text games:

Even with OOP it's not obvious that an inheritance heavy class hierarchy is the only approach. Component entity systems are another way to structure your game objects:

# Answer
> 1 votes
A really solid example would be Frag as FPS written in Haskell. However it will be too complex to grasp without good Haskell knowledge. As for tutorials based on non OOP game programming then this series of articles will explain Entity Systems.

I would point out though that starting with the conclusion and working back is going to be a pretty terrible way to write an article. In fact if you read this article talking about Entity Systems in 'Tony Hawk' games there is a solid case to be made for the idea that OOP is NOT the best technique to use in performant game design.

Good luck on your journey, I hope the articles are illuminating!

# Answer
> 0 votes
Maybe try making a text based game where all the commands are if else type statements. Maybe a more liner game would be best, think something like a choose your own adventure book. That would be a simple example of procedural programming. I suppose you could argue that variables of any sort are objects but they have those even in assembly so I'd say they are okay. This may even be the time to use the dreaded goto statement as even though it may not be best practice it would work in this situation

# Answer
> 0 votes
I've seen a couple of programming tutorials based on non OOP languages, mostly C. If you Google "C game programming tutorial" or similar then you should find them, however there are certainly more tutorials for OOP languages - after all, tutorials are aimed at beginners, and for beginners modern OOP languages (especially those like C# and Java) are easier to get started with than languages like C.

If I were you I would do the reverse however - write a simple game using OOP techniques, and then work backwards converting the same code so that it doesn't rely on any OOP features. With a simple game this should be quite achievable and if you use something like C/C++ a lot of your code will look very similar in both versions.

---
Tags: oop
---


title: Simple Multiplayer CCG System

text:
# Question
Title: Simple Multiplayer CCG System
I am working on a cross plattform Multiplayer CCG (web, android, ios).

Here are my goals in design:

* I want to game to be easly accessible and understandable for non CCG players within the first minute of play.
* a single game should be played by 2 - 4 players a once, without problems if one players drops out during play.
* players should make their next turn simultaneous (without waiting for other to make their turns)

My current approach:

* each Card has a point value for four Elements. In each Turn an Element is (randomly) selected and every Player chooses 1 card out of 3. The Player choosen the card with the highest value for that element wins the Round. After 10 Rounds the players a ranked by how many rounds they won.

Why does this approach seems not optimal?

* It seems really to easy to determin the next best turn. Your own turn is to little affected by the play style of the others. I would love the have a system where some cards are better against other cards. A bit of rock paper scissors where you have to think about what next turn the other players will make or so. But really think freely.

I would love to hear ideas may it be additions or new systems to make a CCG with roughly the stated design goals.

Thanks

# Answer
> 2 votes
The problem here is that your game sounds to be entirely based on chance with no strategy whatsoever. The gameplay boils down to this:

1. build a deck consisting with the highest point valued cards you own, evenly spread between the elements.
2. play games, win or lose by the hand of fate because you always select the highest card of the given element in your hand.
3. buy new cards with the highest point values possible and replace the lowest in your deck.

That's it. That's the entire game. There is no strategy that is 'better' than the above. You're success depends only on luck, and a luck based CCG is doomed to failure.

My advice is to scrap the whole thing and start over. Play some other CCG games to get ideas on how to make great gameplay. In fact, here are some places to start: Final Fantasy 8 and 9 had two simple CCG games that have many of the elements you mentioned. The old Sim City CCG is a totally different kind of CCG and is great for coming up with new ideas in this space. All CCGs seem to want to mimic Magic the Gathering, and that makes sense because it is so popular, but there are many ways to skin this cat. Find a better one.

**Ideas:**

Have players play cards on a grid, first to a spot gets it, once each player lays a card on the grid, they all flip, and the next turn begins. This minimizes the time players spend waiting and encourages them to act fast to be able to plan their next move and to get the best spots. The backs of the cards might indicate only what, about the card, allowed it to be placed legally. Or it could indicate nothing and because it is digital it resolves the problem a game like this would have in reality, human error.

**Free Game Idea**

Cards are square and are lined on the edges with up to 3 elements, better cards have more element icons along more edges, each edge has at least 1 element. A card can have 3 fires on one side or 1 fire, 1 ice, and 1 water; for example.

Cards are placed on a N X N grid (where N is the number of players times 2) in any location, upside down.

Once all the cards are laid, they flip and follow these rules:

Fire beats Ice beats Water beats Fire (add more elements if you wish) However 2 Fire stalemate with 1 Water and 3 Fire beats 1 Water. Cards have ownership that starts with who places them, if a card is beaten by a play, that card becomes owned by the owner of the winning card. When a card changes ownership, any cards next to that card that have not yet been flipped this turn due to being beaten are ALSO beaten and flipped, creating strategic chaining potentials.

Stalemates don't cause ownership changes if two cards have JUST been placed and flipped, but as parts of chains they act as wins. Think of this as all cards gaining 1 of each element if they have just been flipped, by any means.

Once all the slots are filled and flipped, the player with the most cards owned by them on the board wins.

This enables weak cards to still be of strategic value, when played correctly on the board.

In this model there are no unbeatable cards. 3 fires can be beat by 3 waters, cards with 1,1,1 are great for creating chains.

# Answer
> 1 votes
You could try adding a defense element to each card. So instead of having just a card with a fire attack of 4, you now have 4 cards with a fire attack of 4 (one with fire defense, water, etc.). A defense point will negate 1 point of attack from that given element. Then you can also assign different values to the defenses. So now you have N\*(M+1) cards with a fire attack of 4. (N being number of elements, M being max value of a defense, and +1 if the value can be 0).

To expand on your want of a rock-paper-scissor style, certain elements can have an advantage over others. For example, water could either do 2x damage to fire, or simply have a fire attack card never have a water defense more than half its attack value. The winner of each round could be determined by taking the least amount of damage, dealing the most overall, or highest damage dealt to damage taken ratio.

This gives the touch of random luck that people get from opening packs where some cards are obviously better than others, while instilling a bit of strategy. High attack and high defense cards will be harder to get, and those with both high attack and defense will be even harder. Sure people will meta-game it and find the "best" overall deck setup, this happens in every game. But some people may focus on defending against a specific element, or attacking with a specific element. You could also force users to have all the elements, or just limit the number per element so maybe a 2 element deck is possible but a 1 element isn't. This way you can display the percent of each element remaining in an opponent's deck so you can play defensively based on how probable they are to play a certain element.

The overall gameplay is still very simple, and leaves room for many other forms of changes in the future.

---
Tags: game-design, card-game
---


# Question
Title: What is the best way to generate income from mobile games?
As the title states, what is the best way to get income from mobile games? (taking into consideration that creating the games only costs a lot of time and the games are relatively simple)

As I see it, there are multiple ways of getting money from mobile games,

1. Selling them for a fixed price (seems like a high threshold for potential buyers)
2. In-game purchases (I can imagine this only works for several types of games, I don't see this working well for monopoly unless you like really fancy hotels ;)
3. Ingame advertisements / sponsorships

Which way will most likely bring the most profit?

# Answer
I believe the answer you seek is, all 3.

You should release a free version of your game with ad support. Offer a paid version that removes ad support and adds a few bells and whistles. and if it makes sense to do so, have features where you can purchase in-game content.

But to answer the question about how to profit, that is much harder.

To profit you need to consider things not related to the game.

* Time spent on the project
* How much it will cost (art, design, programming, API's, hardware, software, licenses)
* Marketing: this is a big factor, you have to get noticed in the sea of existing games
* maintenance

and many other things related the the SDLC (software development life cycle)

I hope this gets you started on your journey! And remember: If the game isn't fun who is going to want to play it?
> 3 votes

---
Tags: game-design, marketing
---


title: How to properly multi thread an RPG

text:
# Question
Title: How to properly multi thread an RPG
I am working on an RPG type game in Java and I would like to know a few things relating to threading,

What is the best way to implement a "wait for this then do this" without hanging the whole thread? Like waiting for a player to move to a location then pick up an item? or to wait one second then attack?

Currently I am spawning new threads every time I need to wait for something, but that doesn't feel like the best solution.

Any help is appreciated.

EDIT: Clarification and an example of how I currently do things.

User clicks on an item The function walkToAndPickUp(item) is called which is basically this:

Make a new thread so we don't freeze the thread handling input while the player moves.
Tell player to move to the item
While the player is not at the item(The player moves through an update() function called in a different thread, I don't know how else to do it without freezing threads)
Repeat until the player is at the item
If the player is at the item then call delete item from map and add to inventory.

# Answer
> 5 votes
The short answer is: don't. Multithreading will give you more headaches than it saves.

Taking your example in particular:

> User clicks on an item The function walkToAndPickUp(item) is called which is basically this:

I'd rethink things a bit. At any point the state contains (among other things) the PC's target location and the PC's target item.

* A click clears the target item
* The items are ignored in determining the click location. The PC's target location is updated to the point clicked.
* If the point clicked was on an item the target item is set to that item.

Then your game loop will include a move() which checks whether the PC can move towards the target location and if so does, and an interact() which interacts with objects near the PC. Among the interactions are items checking "Am I the target item and within a certain distance of the PC?" If so, they call a pick-me-up routine.

No threads required. No movement code duplicated between moving and picking up items.

# Answer
> 3 votes
Sounds like what you need aren't multiple threads, but coroutines.

See this SO question for more information: https://stackoverflow.com/questions/1247894/coroutines-for-game-design

# Answer
> 3 votes
At some point in the thread you've spawned you're checking for the player to "be in a location". Normally, the check you're doing there isn't blocking in itself, so these conditions are checked by the main logic thread. Checked but not waited on. That's the key, every frame if you like, check for the condition being met, if it is, do the "then" case.

How you implement the condition checking is up to you, but usually there's an array/list of things to check against (in code or data) and the resultant state change function or functor.

It sounds like what you're doing is:

```
while( !condition );
doSomething();

```

Whereas what you need to be doing is more like:

```
if( interestedInDoingSomething && condition )
  doSomething();

```

"User clicks on an item The function walkToAndPickUp(item)" In this case you have a functor called WalkToAndPickup, that is created with the item as an argument, and it ticks until it returns that it's done. Instead of having thread for the fact that you are moving, the object's existence provides the information you need to determine where to walk to and what object to pick up once you get there.

```
functors.insert( new WalkToAndPickup( item ) );
...
while( gameActive )
{
  for functor in functors
  {
    functor.Update();
    if( functor.Done() )
    {
      functors.remove( functor );
      delete functor;
    }
  }
}

```

So what you have here is an impementation that inserts a new functor/task into a container of tasks that are always running. If a task (like walktoitem) finishes, then it gets deleted. What you do inside the functor update is up to you, and will mirror the contents of your threaded system, except you will probably want to either spawn a new functor for each stage of your tasks, or have another internal state for controlling what code to run at what point in the task's sequence of events.

an example of what you might write in your functor's update:

```
update()
{
  switch( state )
  {
    case 0: walkto( item ); if( atItem( item) ) state = 1; break;
    case 1: takeitem( item ); if( gotItem( item) ) state = 2; break;
    case 2: setAsFinished(); break;
  }
}

```

also, don't forget you can insert new functors in the functor list from inside an update. That's how you can chain your dependencies.

# Answer
> 1 votes
Look at animation systems for inspiration. Don't spawn a thread for every item that needs animating! Consider what happens if the user clicks on a different item while your character is still moving towards another item. Then you'll have two threads simultaneously trying to change the same object.

Instead, put actions in a list. Each frame you update each action in the list. When an action is finished or cancelled remove it from the list.

In your walkToAndPickUp example, I would enqueue an action object containing the character and the target location. Each frame I would move the character closer to the target location. On the frame that the location is reached, pick up the item and finish the action by removing it from the list.

To make things simpler, you can compose complex actions out of primitive actions, using an action sequence object. For example, you could make your first example by combining a walkTo action and a pickUp action. Your other example could be combining a wait action followed by an attack action. Then you can easily make new actions, like walkToThenAttack or waitThenWalkTo, without duplicating lots of code.

All characters, NPCs, projectiles, basically anything in the game, should use this system to update and animate their actions.

If the player interrupts the action by clicking elsewhere, the old actions for that character would be removed (or you could block the user from performing more actions until the current one has finished).

---
Tags: java, multithreading, rpg
---


# Question
Title: Multiplayer card game using PHP/Ajax and mysql
I am designing a map game, using PHP and MYSQL. I don't know how to make the players who sign-in to the website to see other players who are also connected to the site and be able to chat with one another.

I want to design the game in such a way that 2 players can play with each other and be able to send messages during the game while others groups are playing at the same time.

I have designed the map game successfully, but the problem is making the player 1 who log-in to site to see the player 2 who will also log-in and both can get connected to play each other. https://i.stack.imgur.com/YyCPG.png

I will appreciate your responses.

# Answer
> 2 votes
Buttons (controlls) and graphics handle on browser. With javascript, there is lot of drawing libraries, well, even game libraries (craftyjs, gameQuery ...).

State a current game has will be on server in a database.

```
table players {id, name, score, actual_game_id ...}
table games {id, name, player_which_is_on_move_id, ... remaining_time (for example) ... }
table card {id, game_it_belongs_to_id, which_player_has_him_in_hand_id, value ...}
table message {id, game_where_it_was_sent_id, player_who_send_it_id, text, ...}

I derived this from thinking about entity relations (may contain mistakes):
player can play only one game, game has N players
card belongs to only one player, player can have N cards
card belongs to only one game, each game has its own cards (so they are not mixed btw games)
only one player is allowed to move at a time
...

```

Communication between player and server is trough AJAX. Player side is coded in javascript, server side in PHP (or similar) + SQL. One problem is that You have to periodically ask/query (chat made by periodical query in AJAX) server whether something new happened (server can not contact You trough AJAX); there might be a way to let server contact You trough something else than polling with AJAX, but I do not know what it is.

* A player sends server messages like "can I play?", "my username and password is ...", "I am moving this card", "I am sending this message to a chat window \> hi folks, this game rocks!" ...
* Server determines whether and how to change database (add message to message table, save the move to tables if it is valid).
* Player periodically queries server "has something new happened", for example when he is waiting for move of a other players.

You have to figure out rules of communication (communication protocol). Also there is a chance, that some of javascript game libraries has methods to help You handle communication.

# Answer
> 0 votes
In SQL, one method could be:

If a player can be in more than one game at a time, you'll need to use a Games table which houses all of the current users mapped to a game\_played identifier

If a player can only be in a single game at a time, make a field for the Player table that states what game\_played ID each is currently attending.

Search for game\_played ID's to help pair players together and reference the data to each other.

As for game state and messages, you can use tables and simply reference the game\_played ID to help sort this out.

---
Tags: game-design, multiplayer, php, card-game
---


# Question
Title: Ray Tracing concers: Efficient Data Structure and Photon Mapping
I'm trying to build a simple ray tracer for specific target scenes. An example of such scene can be seen below.

I'm concerned as to what accelerating data structure would be most efficient in this case since all objects are touching but on the other hand, the scene is uniform.

The objects in my ray tracer are stored as a collection of triangles, thus I also have access to individual triangles.

Also, when trying to find the bounding box of the scene, how should infinite planes be handled? Should one instead use the viewing frustum to calculate the bounding box?

A few other questions I have are about photon mapping. I've read the original paper by Jensen and many more material. In the compact data structure for the photon they introduce, they store photon power as 4 chars, which from my understanding is 3 chars for color and 1 for flux. But I don't understand how 1 char is enough to store a flux of the order of 1/n, where n is the number of photons (I'm also a bit confused about flux vs power).

The other question about photon mapping is, if it would be more efficient in my case to store photons per object (or even per Object's triangle) instead of using a balanced kd-tree.

Also, same question about bounding box of the scene but for photon mapping. How should one find a bounding box from the pov of the light when infinite planes are involved?

EDIT: I would like to add one more question. I've seen in some source codes, that are using russian roulette, scaling the photon's power by the material's diffusivity and dividing by the average color. Is this correct? I thought that the point of the russian roulette was to not have to do this and end up with photons with varying and small powers.

# Answer
> 1 votes
If your camera is always in the same position and orientation, using the view frustum and clipping the infinite planes to those dimensions would certainly be a viable idea. You would no longer have infinite planes. If your camera position/orientation is not fixed then you would have to rebuild your structures with the newly clipped planes every time the camera changes, or you must handle infinite planes differently.

With an infinite plane, the only way a line will not intersect will be if it is parallel to the plane. With a ray, it also won't intersect if the direction of the ray is pointing away from the plane. In both cases, you can handle them separately from your other geometry. I doubt you would have very many infinite planes, so checking them without an acceleration structure is probably fine.

I believe the four chars is actually storing just RGB values as floating point numbers with the same exponent (ie 3 chars for the mantissa of the channels then 1 char for the shared exponent) as outlined in the cited reference from the SIGGRAPH course

The KD-tree is used for efficient nearest neighbour lookups. I don't think storing the photons per object will get you faster lookups so it would not be more efficient.

For the russian roulette, I would say that the sources you have looked at don't seem to be following the algorithm as originally specified. Without seeing them myself, I can't really comment much farther. Perhaps the authors found the results more appealing this way.

---
Tags: data-structure, raytracing
---


title: Starting Java 2D Platformer using LWJGL

text:
# Question
Title: Starting Java 2D Platformer using LWJGL
Getting started on a 2d platforming project in java. I've decided on using LWJGL and OpenGL, but I don't quite know where to start. What is typically the first thing one would work on with a platforming game?

I've never done any game development before, but I'm hoping this will be good practice and hopefully fun to implement and eventually play.

Thanks

# Answer
> 4 votes
Java + 2D + LWJGL = Use Slick library. It's based on LWJGL library and makes it much easier to use for 2D :) In Slick website, they've very easy and quick tutorials, try it out! I'm sure you will LOVE it! ;)

Since your main question is "Where to start", start from Slick Wiki page!

# Answer
> 0 votes
To answer the platform game specific part of your question:

Platform games are traditionally tile based. Tiles are fixed size rectangles which comprise the building blocks of each level; they can have the appearance of stone, or grass or any surface you can imagine within reason. The best way to design them is to ensure that when two identical tiles are placed next to each other, the texture seamless repeats.

A good example of how to design repeating tile sets is here:

http://www.wildbunny.co.uk/blog/2012/03/01/designing-a-retro-pixel-art-tile-set

Tiles are laid out in memory in what is called a 'map'. Each tile is given an identifying number; maps are rectangular arrays containing numerical tile references. An example map might look like this:

```
byte[] map =
{
   01,01,01,01,01,01,01
   01,00,00,00,00,00,01
   01,00,02,02,02,00,01
   01,00,00,00,00,00,01
   01,01,01,01,01,01,01
};

```

Most platform games have multiple layers of these maps; background tiles generally have no collision information associated with them and are purely decorative, mid-ground tiles can be used to mark locations associated with game-logic, like entrances and exits, or for placing AI characters. Foreground tiles are used for collision information and the main body of the actual platforms.

Maps can be connected together using special tiles which indicate an entrance or exit, when collided with the system can unload the current map and load in the new one.

You can read more about platform games in general here:

http://www.wildbunny.co.uk/blog/2011/12/11/how-to-make-a-2d-platform-game-part-1/

Hope that helps!

Cheers, Paul.

---
Tags: opengl, 2d, java, lwjgl, platformer
---


# Question
Title: How to implement a birds eye view of 2D Grid Map using Android
I'm a true beginner with using the android platform and I'm having difficulties on implementing a 2D grid system for a tower defense type game. Where I can place towers on a specific tile and enemies will be able to traverse through tiles etc.

What I would like is a practical explanation of how I could tackle this. A step by step guide for dummies.

This is what I believe are the necessary steps to take, I think I might be wrong but I hope someone could help me out.

1. Calculate the Width and Height of the view I'm working with.
2. Based on that, determine the number of tiles required and their dimensions, (Still not sure how I would do this)
3. Create each tile as a Rectangle object and draw these rectangle on a canvas

I would really be grateful if someone could steer me in the right direction on how to implement a 2D Grid Map using android. I hope the answer to this questions helps the TRUE beginners out there like me.

I have looked at the following links below yet I still feel that I don't trully understand what's going on.

For XNA: 2D Grid based game - how should I draw grid lines?

How to Create a Grid for a 2D Game?

Also a quick note: All my previous game development has been in Java, mostly using Java SE and Swing. I also have good understanding of the game development process, it is only android thats confusing me :S

**Update:** I was actually able to implement, I have decided to post a link to a wiki-page of mine which I have started working on sometime back but not been able to progress further with it.

A simple solution to this can be found here: https://bitbucket.org/iadan/pathfinding/wiki/Home

# Answer
I hope I help with the problem, though my solution might not answer exactly what you ask. I am not familiar with Swing, and usually my android development is done with Adobe Air. But by the powers of Google and my experience I shall try to help.

How to get the screen resolution using Java and Swing: https://stackoverflow.com/questions/3680221/screen-resolution-java

As for the number of tiles you need, that is a game design decision. For simplicity you can decide that all your levels will require a fixed tile size. Based on that you can then divide the screen width and height by the fixed number of tiles you require. So if the screen is 600 X 600 pixels and you require a 10 X 10 grid; each tile would be 60 X 60 pixels.

For added simplicity you could create the tiles at some arbitrary size and add them to the canvas and then scale the canvas to meet your screen size requirements.

Additionally you will want to take into account any UI elements you will have. Using the example above, if you decided to save 50 pixels around the border for UI elements, you would have 500 X 500 to work with making the tiles 50 X 50 pixels.
> 0 votes

# Answer
Take a look at Android SDK sample project Snake. It has TileView class which implements a 2D grid. If you have Android SDK on your computer, you can find it under .../android-sdk/samples/android-\[api number\]/Snake.
> 1 votes

---
Tags: java, android, game-design, maps, tower-defense
---


# Question
Title: The underlying mechanism in 'yield return www' of Unity3D Game Engine
In the Unity3D game engine, a common code sequence for getting remote data is this:

```
WWW www = new WWW("http://remote.com/data/location/with/texture.png");
yield return www;

```

What is the underlying mechanism here?

I know we use the yield mechanism in order to allow the next frame to be processed, while the download is being completed. But what is going on under the hood when we do the `yield return www` ?

What method is being called (if any, on the WWW class)? Is Unity using threads? Is the "upper" Unity layer getting hold of www instance and doing something?

EDIT:

* This question is specifically about Unity3D internals. I'm not interested in explanations of how `yield` statement works in C#. Instead, I'm looking for an inside view of how Unity deals with these constructions, to allow, for example, to WWW to download a piece of data in a distributed manner across several frames.

# Answer
> 8 votes
This is the C# yield keyword in action - its not doing anything special with the `www` object, rather its means something special for the method its contained in. Specifically this keyword can only be used in a method which returns an `IEnumerable` (or `IEnumerator`), and is used to indicate what object will be "returned" by the enumerator when MoveNext is called.

It works because the compiler converts the entire method into a separate class which implements `IEnumerable` (or `IEnumerator`) using a state machine - the net result is that the body of the method itself is not executed until someone enumerates through return value. This will work with any type, there is absolutely nothing special about `WWW`, rather its the containing method which is special.

Take a look at Behind the scenes of the C# yield keyword for some more insight into what sort of code the C# compiler generates, or just experiment and inspect the code yourself using something like IL Spy

---

**Update:** To clarify

* When Unity calls a coroutine that contains a `yield return` statement all that happens is that an enumerator is returned - none of the method body is executed at this point
* To get the method body to execute Unity must call `MoveNext` on the iterator in order to get the first value in the sequence. This causes the method to execute up to the first `yeild return` statement, at which point the caller resumes (and presumably Unity goes on to render the rest of the frame)
* As I understand it Unity normally then goes on to call the `MoveNext` method on the iterator once each subsequent frame, causing the method to execute again up to the next `yield return` statement once each frame, until either the end of the method or a `yield break` statement is reached (indicating the end of the sequence)

The only special bit here (and in a couple of other cases) is that Unity doesn't advance this particular iterator the next frame, instead it only advances the iterator (causing the method to continue executing) when the download has completed. Although there does appear to be a base YieldInstruction class which presumably contains a generic mechanism for signalling to Unity when an iterator should be advanced, the `WWW` class doesn't appear to inherit from this class so I can only assume that there is a special case for this class in the Unity engine.

Just to be clear - the `yield` keyword doesn't do anything special to the `WWW` class, rather its the special handling that Unity gives to the members of the returned enumeration which causes this behaviour.

---

**Update the second:** As for the mechanism that `WWW` uses to download web pages asynchronously it probably uses either the HttpWebRequest.BeginGetResponse Method which will internally use asynchronous IO or alternatively it could use threads (either creating a dedicated thread or by using a thread pool).

# Answer
> 9 votes
`yield` seems to be mainly used in Unity in a coroutine context. To read more about coroutines and why they use C#'s `yield` I recommend this blog article: Unity3D coroutines in detail. Most of the research in this answer comes from that article.

Coroutines in Unity are used to encapsulate tasks which:

1. May take longer than a frame to be rendered (thereby causing slowdowns), and
2. Can be performed separately from the game loop (because the result does not need to be available for the current frame).

Examples of these kinds of tasks are pathfinding (re)calculations or, as is the case in your question, getting data from a website.

To answer your subquestions (in a slightly modified order):

> What method is being called (if any, on the WWW class)? Is the "upper" Unity layer getting hold of www instance and doing something?

Unity's `WWW` class is designed to be yielded from a coroutine. According to the comments on the blog article linked above, the speculative block of code (the '"upper" layer') about `YieldInstruction`s actually contains a switch which also checks for yielded `WWW`s. This code then makes sure the coroutine will finish automatically when the download is done, as described in `WWW`'s reference.

> Is Unity using threads?

In this case, to download the data "without blocking the rest of the game": yes, most likely. (And threading is definitely used to decompress the downloaded data, as evidenced by `WWW.threadPriority`.)

# Answer
> 7 votes
Unfortunately, WWW is implemented internally as native code, meaning that we can't look at the code. From experimentation I can say that

1. `WWW` is *not* derived from `YieldInstruction`, so whatever happens when you `yield` it must be handled by special-case code.
2. I've never obseved any difference between

```
yield return www;

```

and

```
while(!www.isDone)
    yield return null;

```

I think that's the most logical way to implement it, and *most probably* that's what is going on under the hood. But I don't know for sure.
3. Unity does *not* start a new thread for downloading, at least on some platforms (iOS, webplayer). Or if it does, it sets `WWW.isDone` on the main thread. I know this because this code:

```
while(!www.isDone)
    Thread.Sleep(500);

```

doesn't work.

I don't think you can have more specific answers unless someone with access to Unity3d's source code comes here.

# Answer
> 2 votes
Since Unity3D uses C# as their scripting engine I suppose its the standard yield keyword which is built into C#. Basically what it means is that it returns the value of www already so that you can continue while the next iteration it will return the next value, etc... Yield basically creates a state machine and iterator in the background.

---
Tags: unity
---


# Question
Title: How do display a "mucus spreading" effect in a 2D environment?
Here is an example of such a mucus spreading. The substance is spread around the source (in this example, the source would be the main alien building).

*The game is starcraft, the purple substance is called creep.*

How this kind of substance spreading would be achieved in a top down 2D environment? Recalculating the substance progression and regenerate the effect on the fly each frame or rather use a large collection of tiles or something else?

# Answer
According to your comment in the other answers, your problem isn't the creep growing algorithm, but rather the algorithm which chooses which creep tile to use.

Which tile to use depends on whether:

1. the upper tile is infected or not
2. the right tile is infected or not
3. the lower tile is infected or not
4. the left tile is infected or not

That means you will need a total of 16 tiles. You can easily address them with a bitfield. Here is some pseudocode which will choose a different tile for every possible creep constellation:

```
index = 0;
if left tile is creeped then index += 1
if lower tile is creeped then index += 2
if right tile is creeped then index += 4
if upper tile is creeped then index += 8
creep_tile = creep_tiles[index]

```

Note that whenever you change the infection status of a tile, all infected adjacent tiles need to be re-evaluated, because their neighborhood has now changed.

How to design the 16 tile graphics so that they fit together nicely is a (new) question for a graphic designer.
> 7 votes

# Answer
A while ago I read a strategy article that explained in detail how creep spreads in Starcraft 2, I'm struggling to find it now but I remember that its fairly simple and works a bit like this

* The Starcraft 2 map is split into tiles
* For each source of creep, every "tick" choose a random tile which is elegible for creep to spread to, and spread creep onto that tile
* Creep may spread to any tile which is
    + Adjacent either to another tile with creep on it, or adjacent to the source of the creep
    + Within a given range of the source of creep
    + Not a cliff

The easiest way to track which tiles creep has spread to is probably just a flag for each tile - dont' try to re-calculate it each turn.

The time between "ticks" can be used to control the spread rate of the creep, alternatively you could allow creep to spread to multiple tiles each "tick", or even randomise the time between ticks.

The above algorithm has the effect that creep spreads faster if it is blocked in by cliffs on either side, however you could instead choose a random tile within range of the source of creep and then only spread creep to that tile if it is not a cliff.
> 2 votes

---
Tags: 2d, algorithm, graphic-effects
---


# Question
Title: How do I constrain a specific area of an actor to mouse X and Y?
I recently watched this tutorial "Actor Constraints in GameSalad" detailing how to constrain the center of an actor to the mouse X and Y, but I would like to constrain the relative clicked pixel of the actor to the mouse X and Y, not the center of the actor.

In other words, I want to avoid the "jumping" nature of "constrain self.Position.X to game.Mouse.Position.X" when I click and drag.

# Answer
> -1 votes
That's simple. When the actor is clicked, store the difference between each coordinate and the (0,0) spot (wherever that might be) in a couple of variables. Then as the mouse is moved and you move the actor, subtract those stored values from the mouse position to determine where the actor should be placed.

Note, I have no knowledge of Gamesalad in particular. It does have variables right?

---
Tags: gamesalad
---


# Question
Title: 3D rotation tool. How can I add simple extrusion?
The 3D rotation tool is excellent but it only lets you rotate 2D objects, this means my object is wafer thin.

Is there any way to add simple extrusion or depth to a symbol?

I don't really want to use any 3rd party libraries like Away3D or Papervision, this is overkill for my simple 2D game. I only want to do this creating a couple motion tweens if possible.

**More Details:**

Below is what my symbol looks like (just with a bit more color). The symbol does a little 3D rotation and then flies away, it's just for something like a scoreboard within the app.

# Answer
For all that you don't want to use 3rd Party 3D frameworks, a simple solution for the rounded corners won't be that simple.

@Jari Komppa - his approach is the way to do it, but you'll spend some time making all the corner pieces. Each corner will probably need 3 polygons to replicate the curve satisfactorily. So you'd have to add 15 polygons for the rounded edges and another 7 for the other side and back faces. If that works for you, have at it. The nice thing about something like Away3D is that you can import a 3ds or other model and use that instead. No trying to work out the intricacies of 3D model in code.
> 1 votes

---
Tags: flash, flash-cs5
---


# Question
Title: How to hide assets from user? ( e.g.: a png file )
I think the title is quite self-explaining, still this is a **big area** I think, so let me drop a few words:

I've got a simple experiment game project going, and I want **to make sure**, that **the user isn't messing with the game assets** like player skin etc.

In my opinion the best way would be that on production I would merge all the assets into one file and the application **would check the hash** of that file, so it could detect the corrupted data.

Is this an acceptable practice? There must be sum libraries / applications which are targeting this problem, could you guide me on this?

Project details: unix/linux, c++, sdl

# Answer
My answer to this question won't be complete, because there is no real good way to achieve what you want.

Assume you would pack all your assets in one zip file and compute the hashes. This leads to the problem that you need to recompile your project if you hardcode your expected hashes. However if you save the hash in another external location, you would need to protect that, too.

One method to protect your assets I often rely on is using PhysicsFS to pack my assets in different packed zip files. In order to protect them, you could use some kind of symmetric encryption to secure your archives. If you do not plan any AAA-game this should be fairly enough to protect everything. But keep in mind, too much encryption etc. won't be useful and eventually decrease performance if you load your assets on-the-fly.
> 1 votes

# Answer
Don't make it too easy for hackers by putting each individual image in its own file or whatever, but don't bother with encryption because the determined ones will just break it, and pushing it to slow them down will just slow down your game and its development.

Blizzard's MPQ format has encryption, and it has been cracked.

The big name games tend to use some variation of a well-indexed propietary archive file format with maybe basic compression.
> 3 votes

---
Tags: c++, sdl, linux, encryption
---


title: GLSL custom interpolation filter

text:
# Question
Title: GLSL custom interpolation filter
I'm currently building a fragment shader which is using several textures to render the final pixel color.

The textures are not really textures, they are in fact "input data" to be used in the formula to generate the final color.

The problem I've got is that the texture are getting bi-linear-filtered, and therefore the input data as well. This results in many unwanted side-effects, especially when final rendered texture is "zoomed" compared to original resolution.

Removing the side effect is a complex task, and only result in "average" rendering. I was thinking : well, all my problems seems to come from the "default" bi-linear filtering on these input data. I can't move to GL\_NEAREST either, since it would create "blocky" rendering. So i guess the better way to proceed is to be fully in charge of the interpolation.

For this to work, i would need the input data at their "natural" resolution (so that means 4 samples), and a relative position between the sampled points. Is that possible, and if yes, how ?

\[EDIT\] Since i started this question, i found this internet entry, which seems to (mostly) answer my needs. http://www.gamerendering.com/2008/10/05/bilinear-interpolation/

One aspect of the solution worry me though : the dimensions of the texture must be provided in an argument. It seems there is no way to "find this information transparently". Adding an argument into the rendering pipeline is unwelcomed though, since it's not under my responsibility, and translates into adding complexity for others.

# Answer
> the dimensions of the texture must be provided in an argument. It seems there is no way to "find this information transparently".

What, are you stuck in GL 2.1 land? We've had `textureSize` in GLSL for years now.
> 3 votes

---
Tags: textures, glsl, interpolation
---