# Question
Title: Problems with Level Architect, Citrus Engine, Flash
I am using the Citrus Engine to make a Flash game, and the Level Architect doesn't work well for me. Firstly, when I first launch it and open my project and my level, nothing is shown, no assets and not anything I have previously done with my level. To fix it, I open another project. The other project works fine, meaning I can see the assets and the level. Then I go back to the actual project I am working on, and the problem is fixed, only it does not fix the second problem: I can't add my own assests. I follow the manual and add tags like this: `[Property(value="0")]`

But it doesn't change a thing in the level architect window (even after I close and reopen it). Any ideas? Thanks!

Here's the code of the class I want to be shown in the Level Architect:

```
package {

import com.citrusengine.objects.PhysicsObject;
import com.citrusengine.objects.platformer.Sensor;

import flash.utils.clearTimeout;
import flash.utils.setTimeout;

/**
 * @author Aymeric
 */
public class Teleporter extends Sensor {

    [Property(value="0")]
    public var endX:Number=0;
    [Property(value="0")]
    public var endY:Number=0;
    public var object:PhysicsObject;

    [Property(value="0")]
    public var time:Number = 0;

    public var needToTeleport:Boolean = false;

    protected var _teleporting:Boolean = false;

    private var _teleportTimeoutID:uint;

    public function Teleporter(name:String, params:Object = null) {
        super(name, params);
    }

    override public function destroy():void {

        clearTimeout(_teleportTimeoutID);

        super.destroy();
    }

    override public function update(timeDelta:Number):void {

        super.update(timeDelta);

        if (needToTeleport) {

            _teleporting = true;

            _teleportTimeoutID = setTimeout(_teleport, time);

            needToTeleport = false;
        }

        _updateAnimation();
    }

    protected function _teleport():void {

        _teleporting = false;

        object.x = endX;
        object.y = endY;

        clearTimeout(_teleportTimeoutID);
    }

    protected function _updateAnimation():void {

        if (_teleporting) {
            _animation = "teleport";
        } else {
            _animation = "normal";
        }
    }
}
}

```

# Answer
Here are some things to check:

1. Are you extending one of the Citrus classes (CitrusSprite, PhysicsObject)? If so can we see that class's code?
2. Do you have the \[Property\] tag in the right place, above a public var or a public set function? If so can we see that code.
3. Make sure the code for the project is in the folder path Level Architect expects it to be as mentioned in the instructions for setting up your IDE.

https://docs.google.com/document/pub?id=1fVTAg6EET9znfCRHzlqF-ByJqFvScacGt0DerIJY4L0

I think it might be one of those things, let me know and I'll help out.
> 1 votes

---
Tags: flash
---


# Question
Title: Is an in-app purchase required to unlock game in order to bypass pirating acceptable?
I'm considering writing a mobile game and looking at distribution. The game will have a server requirement, which means I will have to pay for bandwidth, hosting, processor time, etc. Because of that I'll need to make at least a little money off this thing. According to the press piracy is rampant in the android community. To get around this, I'm thinking of implementing a simple model where the game is free, perhaps allowing play for X number of turns or something, and then requiring an in-app purchase to continue to play. I would clearly explain this in the app description, and the in-app purchase would be managed per account so it would be linked to your google play account so you wouldn't have to re-purchase every time you get a new device.

Would gamers accept this model or see it as unreasonable?

# Answer
That's certainly a legitimate approach, how successful it will be is another matter.

This article is about an iOS game called Gasketball that took a similar approach and how that worked out for them (spoiler: not so great). Based on this article I don't think players are enraged by the idea of getting a free-to-play game then paying some amount of money to unlock the full game.
> 6 votes

# Answer
There's no real way of knowing without trying it. The variability of success in the mobile market seems very high from everything I've read.

In your place, I'd probably adopt a shareware model. Divide the content up into chapters and offer the first one for free, with the subsequent chapters available through IAP individually or as a bundle for a discount. I've seen this model used for a number of free-to-download mobile games, although I don't know how successful it is.
> 5 votes

# Answer
You could simply provide buyers with a username/password upon purchase of your game and allow them to sign in, actually they could sign in with their googleID which they will provide to you during their purchase and your will add to your server as a payed customer. I did something similar with an education service, it could not be very tricky, could it?

How would you monitor how many turns they played? Sounds like a big database... that could be bypassed somehow by faking user ID, I suggest limiting them to a certain area of the game map in the free version and letting them explore everything in the full version.

Good luck with your project.
> 0 votes

---
Tags: android, monetization
---


# Question
Title: Scrolling though objects then creating a new instace of this object
In my game when pressing the right mouse button you will place an object on the ground. all objects have the same super class (GameObject). I have a field called selected and will be equal to one certain gameobject at a time. when clicking the right mouse button it checks whats the instance of selected and that how it determines which object to place on the ground. code exapmle: t is the "slot" for which the object will go to.

```
if (selected instanceof MapleTree) {
    t = new MapleTree(game,highLight);
} else if (selected instanceof OakTree) {
        t = new OakTree(game,highLight);
}

```

Now it has to be a "new" instance of the object. Eventually my game will have hundreds of GameObjects and I don't want to have a huge if else statement. How would I make it so it scrolls though the possible kinds of objects and if its the correct type then create a new instance of it...?

When pressing E it will switch the type of selected and is an if else statement as well. How would I do it for this too? here is a code example:

```
if (selected instanceof MapleTree) {
        selected = new OakTree(game);
} else if (selected instanceof OakTree) {
    selected = new MapleTree(game);
}

```

# Answer
What about making clones or factories?

For clones, you could just call object.clone(). This would make another instance of this object type. Though I'm not sure if they will share references, so may not be the best way.

Thinking a little more, I think you could use Java Reflection library.

Assuming you just have one constructor with no parameters, this could work:

```
Constructor ctor = selected.getClass().getDeclaredConstructors()[0];
ctor.setAccessible(true);
t = (GameObject)ctor.newInstance();

```

If you have parameters for your constructor like in your example you can use something like this:

```
Constructor ctor = selected.getDeclaredConstructor(game.getClass());

```

But be aware that this may be slow. So there may be better options for this.
> 1 votes

---
Tags: java, selection, instancing, gameobject
---


# Question
Title: Permanently Sync a wiimote with a computer
i have tried to look up many ways to sync up my wiimotes to my computer so that i can program games with it, but every time it only syncs them up temporarily, or if it says it can permanently sync it, it doesn't actually do it. it gets tiresome when i have to keep on reconnecting it every time i want to save battery life. how would i be able to sync up my wiimote to my computer so that if i turn off my wiimote, i can just hit any button and it will automatically sync it up?

Edit: I have looked here: http://wiibrew.org/wiki/Wiimote under Bluetooth pairing for some advice, but I have no idea how to export the char array to the window (i am using the standard pairing with a Bluetooth device, but instead of pairing without a code, i use the "enter device's pairing code" section. this should work, but I'm stuck at how to enter the weird characters that aren't on the keyboard).

# Answer
> 1 votes
There are some problems with doing this, specifically with the new model of wiimotes that Nintendo has released and has seemed to use to replace the old model. There is a lot of open source code available for setting it up though.

Here is a link documenting some of the new wiimote plus issues: http://code.google.com/p/dolphin-emu/issues/detail?id=5011

Also, I would examine how Dolphin deals with syncing. Hope that helps. :)

Edit: I believe automatic syncing in the way that you described would require you to write software. :/

---
Tags: wii, bluetooth
---


# Question
Title: Pre baked fractures and explosion : I need an answer for C++
What are the prebaked or precomputed explosions or fractures from a programmer viewpoint ?

I would like to know how to achieve this in C++ and how this things are usually considered (they are animations? textures?), it would be perfect if there will be some examples available or someone that can picture a broad view about this.

I need to add a really small support for this in my code and i need an hint about how to start, i would like to do this on my own without other libraries.

# Answer
The general approach is to replace models with broken versions of those. There are two ways to go from here: manually building the broken versions or generating them. If you work with an artist, the first way is much easier than the second. Some of the modelling apps may even have tools that generate broken versions of meshes.

Generation is usually done by adding an extra material, slicing the mesh using planes, triangulating the created hole edge loops and applying the new material on those triangles. However, this sounds much easier than it actually is. For the right effect, the input mesh must have no visible holes (which means that, for example, bottoms of buildings must be closed). The difficulties in designing the algorithms and data layouts may arise in multimaterial setups where each part of mesh isn't closed while everything put together is.

Since generation is such an insane thing to attempt, it should only be done on procedurally generated meshes. For everything else, you will need an artist and there's no sane way around that.

Physics for everything is done as usual: generate convex hulls (libraries usually have something that will help with this) for each mesh and create the bodies.
> 1 votes

# Answer
Pre-baked fractures are typically simple object swaps.

Consider a vase getting hit by a bullet. Instead of having one vase, you have two: an intact one and one in pieces. When the bullet hits, you remove the intact vase from the scene and place the broken one in.
> 1 votes

---
Tags: c++, pre-production
---


# Question
Title: Using an iPhone as a controller for a flash game
How can I use an iPhone as a controller for a flash game, as described here?

# Answer
I don't think it's hard to do assuming your setup is something like this

phone --- remote server --- flash

The flash app and the app on the phone need to share a code to be bonded togheter. You can ask the user to insert a code manually or you can use a QR code.

The flash app use a socket to connect to the remote server, the phone app do the same. Both the apps send the shared code to the server and the server now knows that the input from the phone app need to be redirected to the flash app with the same code.
> 1 votes

---
Tags: iphone, flash, controllers
---


title: Drawing multiple Textures as tilemap

text:
# Question
Title: Drawing multiple Textures as tilemap
I am trying to draw a 2d game map and the objects on the map in a single pass. Here is my OpenGL initialization code

```
// Turn off unnecessary operations
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_STENCIL_TEST);
glDisable(GL_DITHER);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);

// activate pointer to vertex & texture array
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);

```

My drawing code is being called by a NSTimer every 1/60 s. Here is the drawing code of my world object:

```
- (void) draw:(NSRect)rect withTimedDelta:(double)d {
  GLint *t;
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, [_textureManager textureByName:@"blocks"]);
  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

  for (int x=0; x<[_map getWidth] ; x++) {
    for (int y=0; y<[_map getHeight] ; y++) {
      GLint v[] = {
        16*x ,16*y,
        16*x+16,16*y,
        16*x+16,16*y+16,
        16*x ,16*y+16
      };

      t=[_textureManager getBlockWithNumber:[_map getBlockAtX:x andY:y]];

      glVertexPointer(2, GL_INT, 0, v);
      glTexCoordPointer(2, GL_INT, 0, t);
      glDrawArrays(GL_QUADS, 0, 4);

    }
  }
}

```

(\_textureManager is a Singelton only loading a texture once!) The object drawing codes is identical (except the nested loops) in terms of OpenGL calls:

```
- (void) drawWithTimedDelta:(double)d {
  GLint *t;
  GLint v[] = {
    16*xpos ,16*ypos,
    16*xpos+16,16*ypos,
    16*xpos+16,16*ypos+16,
    16*xpos ,16*ypos+16
  };
  glBindTexture(GL_TEXTURE_2D, [_textureManager textureByName:_textureName]);

  t=[_textureManager getBlockWithNumber:12];

  glVertexPointer(2, GL_INT, 0, v);
  glTexCoordPointer(2, GL_INT, 0, t);
  glDrawArrays(GL_QUADS, 0, 4);
}

```

As soon as my central drawing routine calls the two drawing methods the second call overlays the first one. i would expect the call to world.draw to draw the map and "stamp" the objects upon it. Debugging shows me, that the first call is performed correctly (world is being drawn), but the following call to all objects ONLY draws the objects, the rest of the scene is getting black.

I think i need to blend the drawn textures, but i cant seem to figure out how.

Any help is appreciated. Thanks

PS: Here is the github link to the project. It may not be in sync of my post here, but for some more in-depth analysis it may help.

# Answer
> 5 votes
Looking at the art assets in your github I think I know what the problem is.

What you need is alpha blending. Save your sprites with an alpha channel (or convert the background to zero alpha when loading the textures).

Set up blend function like this:

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

That tells OpenGL to blend (mix) the pixel data that's already on the screen with the pixel data from the texture based on the texture's alpha value.

---
Tags: opengl, objective-c, macos
---


# Question
Title: How do I create a Loading Scene in SLick?
I actually wanted just a fake loading scene. For a fake loading scene, how do I make a time variable or a time Method? I'm still a fresh java programmer!

# Answer
As fresh java programmer, at first try to have basics, then do it through an example and then you are expert (use professional libraries for your projects).

Basics #

Core Example #

Open Source Library #

**EDIT:** `Regarding loading Scene in SLick`

Slick provides a way to get this loading bar style initialisation - called deferred loading. When deferred loading is enabled all the calls to load resoures (images, sounds, music, fonts etc) are wrapped in the library to load only the explicit data required for the resource immediately.

```
public void render(GameContainer container, Graphics g) {
    g.drawString("Loaded: "+lastLoaded, 100, 100);
}

public void update(GameContainer container, int delta) throws SlickException {
    if (LoadingList.get().getRemainingResources() > 0) {
        DeferredResource nextResource = LoadingList.get().getNext();
        nextResource.load();
        lastLoaded = nextResource.getDescription();
    } else {
        // loading is complete, do normal updat ehere
    }
}

```

For more details, go through the followings
> 2 votes

# Answer
You can use java Timer. Draw a rect somewhere on your screen as a progress bar and increase his width regarding the elapsed/remaining time, it can be done with a really simple percentage operation.

```
timer = new Timer(...)
timer.addActionListener(yourSceneLoader)

```

*yourSceneLoader* can be a class in charge of handling the loading of your scenes, regarding the code above it should implements *ActionListener* and in the *actionPerformed* method:

```
public void actionPerformed() {
    updateProgressBar() //do the calculations in this method
}

```

You don't necessarily have to use a *Timer* but it's a way to achieve what you want and you can easily control how fast the progress bar progress.

Also if you want to do *real* loading, you can read this.
> 1 votes

---
Tags: java, slick
---


# Question
Title: Information about rendering, batches, the graphical card, performance etc. + XNA?
I know the title is a bit vague but it's hard to describe what I'm really looking for, but here goes.

When it comes to CPU rendering, performance is mostly easy to estimate and straightforward, but when it comes to the GPU due to my lack of technical background information, I'm clueless. I'm using XNA so it'd be nice if theory could be related to that.

So what I actually wanna know is, what happens when and where (CPU/GPU) when you do specific draw actions? What is a batch? What influence do effects, projections etc have? Is data persisted on the graphics card or is it transferred over every step? When there's talk about bandwidth, are you talking about a graphics card internal bandwidth, or the pipeline from CPU to GPU?
*Note:* I'm not actually looking for information on *how* the drawing process happens, that's the GPU's business, I'm interested on all the overhead that precedes that.

I'd like to understand what's going on when I do action X, to adapt my architectures and practices to that.

Any articles (possibly with code examples), information, links, tutorials that give more insight in how to write better games are very much appreciated. Thanks :)

# Answer
I like to think of performance in terms of "**limits**". It's a handy way to conceptualise a fairly complicated, interconnected system. When you have a performance problem, you ask the question: "What limits am I hitting?" (Or: "Am I CPU/GPU bound?")

You can break it down into multiple levels. At the highest level you have the CPU and the GPU. You might be CPU bound (GPU sitting idle waiting for CPU), or GPU bound (CPU is waiting on GPU). Here is a good blog post on the topic.

You can break it down further. On the **CPU** side, you might be using all your cycles on data already in the CPU cache. Or you might be **memory limited**, leaving the CPU idle waiting for data to come in from main memory (so optimise your data layout). You could break it down further still.

(While I am doing a wide overview of performance regarding XNA, I will point out that an allocation of a reference type (`class` not `struct`), while normally cheap, could trigger the garbage collector, which will burn a lot of cycles - especially on Xbox 360. See here for details).

On the **GPU** side, I'll start out by pointing you to this excellent blog post which has lots of details. If you want an *insane* level of detail on the pipeline, read this series of blog posts. (Here's a simpler one).

To put it here simply, some of the big ones are the: "**fill limit**" (how many pixels you can write to the backbuffer - often how much overdraw you can have), "**shader limit**" (how complicated your shaders can be and how much data you can push through them), "**texture-fetch/texture-bandwidth limit**" (how much texture data you can access).

And, now, we come to the big one - which is what you're really asking - where the CPU and GPU have to interact (via the various APIs and drivers). Loosely there is the "**batch limit**" and "**bandwidth**". (Note that part one of the series I mentioned earlier goes into *extensive* details.)

But, basically, a **batch** (as you already know) happens whenever you call one of the `GraphicsDevice.Draw*` functions (or part of XNA, like `SpriteBatch`, does this for you). As you no doubt have already read, you get a few thousand of these per frame. This is a CPU limit - so it competes with your other CPU usage. It's basically the driver packaging up everything about what you have told it to draw, and sending it off to the GPU.

And then there is the **bandwidth** to the GPU. This is how much raw data you can transfer there. This includes all the state information that goes with batches - everything from setting rendering state and shader constants/parameters (which includes things like world/view/project matrices), to vertices when using the `DrawUser*` functions. It also includes any calls to `SetData` and `GetData` on textures, vertex buffers, etc.

At this point I should say that anything that you can call `SetData` on (textures, vertex and index buffers, etc), as well as `Effect`s - remains in GPU memory. It is not constantly re-sent to the GPU. A draw command that references that data is simply sent with a pointer to that data.

(Also: you can only send draw commands from the main thread, but you can `SetData` on any thread.)

XNA complicates things somewhat with its render state classes (`BlendState`, `DepthStencilState`, etc). This state data *is* sent per draw call (in each batch). I am not 100% sure, but I am under the impression that it is sent lazily (it only sends state that changes). Either way, state changes are cheap to the point of free, relative to the cost of a batch.

Finally, the last thing to mention is the internal **GPU pipeline**. You don't want to force it to flush by writing to data that it still needs to read, or reading data that it still needs to write. A pipeline flush means it waits for operations to finish, so that everything is in a consistent state when data is accessed.

The two particular cases to watch out for are: Calling `GetData` on anything dynamic - particularly on a `RenderTarget2D` that the GPU may be writing to. This is extremely bad for performance - don't do it.

The other case is calling `SetData` on vertex/index buffers. If you need to do this often, use a `DynamicVertexBuffer` (also `DynamicIndexBuffer`). These allow the GPU to know that they will be changing often, and to do some buffering magic internally to avoid the pipeline flush.

(Also note that dynamic buffers are faster than `DrawUser*` methods - but they have to pre-allocated at the maximum required size.)

... And that's pretty much everything I know about XNA performance :)
> 20 votes

---
Tags: xna, directx, rendering, performance, gpu
---


# Question
Title: How to get all child with same tag from CCLayer?
Actually i am working with cocos2d Game. I am using CCLayer for particular scene. now there are so many buttons means CCMenuitems are available. I want to disable that all menuitems having same tags.

# Answer
I'm not sure what the best way to do this is but the way I would do is by putting all the children into an array. Then iterate trough the array:

```
WhateverYouNeed *thingInArray;
CCArray *theArray = [self children];
for thingInArray in theArray {
  if ([thingInArray tag] == whateverTheTagIs)
    do some stuff to thingInArray
}

```
> 3 votes

---
Tags: cocos2d-iphone, cocos2d
---


# Question
Title: How can I draw crisp per-pixel images with OpenGL ES on Android?
I have made many Android applications and games in Java before, however I am very new to OpenGL ES. Using guides online, I have made simple things in OpenGL ES, including a simple triangle and a cube.

I would like to make a 2D game with OpenGL ES, but what I've been doing isn't working quite so well, as the images I draw aren't to scale, and no matter what guide I use, the image is always choppy and not the right size (I'm debugging on my Nexus S).

How can I draw crisp, HD images to the screen with GL ES?

Here is an example of what happens when I try to do it:

And the actual image:

Here is how my texture is created:

```
//get id
int id = -1;
gl.glGenTextures(1, texture, 0);
id = texture[0];

//get bitmap
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ball);

//parameters
gl.glBindTexture(GL10.GL_TEXTURE_2D, id);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
        GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
        GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
        GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
        GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
        GL10.GL_REPLACE);

GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

//crop image
mCropWorkspace[0] = 0;
mCropWorkspace[1] = height;
mCropWorkspace[2] = width;
mCropWorkspace[3] = -height;
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);

```

# Answer
> 2 votes
You need to change the `GL_TEXTURE_MAG_FILTER` to `GL_LINEAR`.

`gl.glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);`

# Answer
> 2 votes
There is a couple of parameters you need to set on the texture, the first one is to tell OpenGL what to do if the texture need to be shrunk or magnified to match the rendered image. For a blurred image you should utilize another one. For a crisp and clean rendering image then other. For more details, followings #

* `GL_TEXTURE_MAG_FILTER` : If the texture is smaller it needs to be magnified that is done with the magnification function
* `GL_TEXTURE_MIN_FILTER` : If the texture needs to be scaled down using the minification function
* `GL_LINEAR` : For a blurred image
* `GL_NEAREST` : For a crisp and clean rendering image

Utilize **`GL_NEAREST`**

> gl.glTexParameterf(GL\_TEXTURE\_2D, GL\_TEXTURE\_MAG\_FILTER, GL\_NEAREST);

# Answer
> 1 votes
What you want to achieve is called "pixel perfect texture mapping".

You need to call

```
gl.glOrthof(0, displayWidth, 0 , displayHeight, 0.0f, 100.0f);

```

in your initialization function. This will set 1 OpenGL unit equals to 1 pixel. OpenGL coordinates will be (0,0) for the top-left angle and (width, height) for the bottom-right angle.

---
Tags: android, java, opengl-es2
---


# Question
Title: Better way to implement iPhone Games targeting iPhone 4, 4S & 5
**iPhone 5:**

* 4″ at 1146 x 640 resolution retina display

**iPhone 4, 4S:**

* 3.5″ at 960 x 640 resolution retina display

We are developing games targeting iPhone 4, 4S & 5.

* What graphics resource ratio would be better with less time and investment?
* Which ratio would be easy to integrate with targeting device with less coding?

# Answer
The answer is : depends on the type of the game.

For example, if the game is a racing 3D game, you can modify the aspect ratio of the screen, but all the assets stay the same. If it's a board game with zoom - the same applies - you will just see more of the board.

The main problem will be, IMHO, GUI. Note however, that in some type of games it would be perfectly ok to leave it exactly as-is; it would make steering with on-screen controls easier, while keeping the gui visible.

As the footnote: iPhone 5 has the same horizontal resulotion as 4S. Whilst you can just play 4S games on 5 in letterbox mode, opposite isn't possible. The letterbox space can be filled not only with extending of the game display, but, as I mentioned earlier, larger gui or controls
> 0 votes

---
Tags: graphics, iphone
---


# Question
Title: Networking library compatible C++ and Java
There is any networking library like **eNet** compatible with *Java* and *C++*?

'm trying to find a way to communicate an Android game in Java with a C + + server, but I prefer to use a network library instead raw sockets.

I've found a java-enet, but I don't know if it's a mature project or compatible with eNet C version.

# Answer
There is ICE. It's cross platform network middleware, which is quite powerful. It has C++ and Java binds, also with android support IIRC.
> 1 votes

---
Tags: c++, java, android, networking
---


# Question
Title: Two graphical entities, smooth blending between them (e.g. asphalt and grass)
Supposedly in a scenario there are, among other things, a tarmac strip and a meadow. The tarmac has an asphalt texture and its model is a triangle strip long that might bifurcate at some point into other tinier strips, and suppose that the meadow is covered with grass.

What can be done to make the two graphical entities seem less cut out from a photo and just pasted one on top of the other at the edges? To better understand the problem, picture a strip of asphalt and a plane covered with grass. The grass texture should also "enter" the tarmac strip a little bit at the edges (i.e. feathering effect).

My ideas involve two approaches:

* put two textures on the tarmac entity, but that involves a serious restriction in how the strip is modeled and its texture coordinates are mapped

or

* try and apply a post-processing filter that mimics a bloom effect where "grass" is used instead of light. This could be a terrible failure to achieve correct results.

So, is there a better or at least a more obvious way that's widely used in the game dev industry?

*UPDATE:*

This is a conceptual question, I do not require a specific shading language or framework. In real life, I use Cg with Ogre for rendering experiments. If I supply two textures and two different texture coordinate sets for the tarmac entity, I can analyze the second texture coordinate set in the fragment shader and do some blending depending on the .y component of the *uv* pair, but that requires the artist to hand-craft every asphalt/tarmac runway in the scenario and it looked to me that this is probably the wrong way to tackle the issue.

# Answer
Multi-texturing.

Add a weight to each texture by adding extra texcoords in a shader to your vertex declaration.

You haven't supplied what language you'd like this in (or even whether it's a programming question, but that's an assumption on my part), but Riemers provides a good tutorial using C# and XNA and also explains the concept *here*.
> 5 votes

---
Tags: textures, rendering, terrain-rendering
---


# Question
Title: GameplayScreen does not contain a definition for GraphicsDevice
Long story short: I'm trying to intergrate my game with Microsoft's Game State Management. In doing so I've run into some errors, and the latest one is in the title. I'm not able to display my HUD for the reasons listed above.

Previously, I had much of my code in my Game.cs class, but the GSM has a bit of it in Game1, and most of what you have drawn for the main screen in your GameplayScreen class, and that is what is causing confusion on my part.

I've created an instance of the GameplayScreen class to be used in the HUD class (as you can see below). Before integrating with the GSM however, I created an instance of my Game class, and all worked fine.

It seems that I need to define my graphics device somewhere, but I am not sure of where exactly. I've left some code below to help you understand.

```
 public class GameStateManagementGame : Microsoft.Xna.Framework.Game
{
    #region Fields

    GraphicsDeviceManager graphics;
    ScreenManager screenManager;
            // Creates a new intance, which is used in the HUD class
    public static Game  Instance;

    // By preloading any assets used by UI rendering, we avoid framerate glitches
    // when they suddenly need to be loaded in the middle of a menu transition.
    static readonly string[] preloadAssets =
    {
        "gradient",
    };

    #endregion

    #region Initialization

    /// <summary>
    /// The main game constructor.
    /// </summary>
    public GameStateManagementGame()
    {
        Content.RootDirectory = "Content";

        graphics = new GraphicsDeviceManager(this);
        graphics.PreferredBackBufferWidth = 1280;
        graphics.PreferredBackBufferHeight = 720;
        graphics.IsFullScreen = false;
        graphics.ApplyChanges();

        // Create the screen manager component.
        screenManager = new ScreenManager(this);

        Components.Add(screenManager);

        // Activate the first screens.
        screenManager.AddScreen(new BackgroundScreen(), null);
        //screenManager.AddScreen(new MainMenuScreen(), null);
        screenManager.AddScreen(new PressStartScreen(), null);
    }

namespace Pong
{
    public class HUD
    {
        public void Update(GameTime gameTime)
        {

         // Used in the Draw method
            titleSafeRectangle = new Rectangle
                (GameplayScreen.Instance.GraphicsDevice.Viewport.TitleSafeArea.X,
                GameplayScreen.Instance.GraphicsDevice.Viewport.TitleSafeArea.Y,
                GameplayScreen.Instance.GraphicsDevice.Viewport.TitleSafeArea.Width,
                GameplayScreen.Instance.GraphicsDevice.Viewport.TitleSafeArea.Height);

        }
    }
}

   class GameplayScreen : GameScreen
{
    #region Fields
    ContentManager content;
    public static GameStates gamestate;
    private GraphicsDeviceManager graphics;
    public int screenWidth;
    public int screenHeight;
    private Texture2D backgroundTexture;
    private SpriteBatch spriteBatch;
    private Menu menu;
    private SpriteFont arial;
    private HUD hud;
    Animation player;

    // Creates a new intance, which is used in the HUD class
    public static GameplayScreen Instance;

   public GameplayScreen()
    {
       TransitionOnTime = TimeSpan.FromSeconds(1.5);
       TransitionOffTime = TimeSpan.FromSeconds(0.5);
    }

    protected void Initialize()
    {

        lastScored = false;
        menu = new Menu();
        resetTimer = 0;
        resetTimerInUse = true;
        ball = new Ball(content, new Vector2(screenWidth, screenHeight));
        SetUpMulti();
        input = new Input();
        hud = new HUD();

        // Places the powerup animation inside of the surrounding box
        // Needs to be cleaned up, instead of using hard pixel values
        player = new Animation(content.Load<Texture2D>(@"gfx/powerupSpriteSheet"), new Vector2(103, 44), 64, 64, 4, 5);

        // Used by for the Powerups
        random = new Random();
        vec = new Vector2(100, 50);
        vec2 = new Vector2(100, 100);
        promptVec = new Vector2(50, 25);
        timer = 10000.0f; // Starting value for the cooldown for the powerup timer
        timerVector = new Vector2(10, 10);

        //JEP - one time creation of powerup objects
        playerOnePowerup = new Powerup();
        playerOnePowerup.Activated += PowerupActivated;
        playerOnePowerup.Deactivated += PowerupDeactivated;

        playerTwoPowerup = new Powerup();
        playerTwoPowerup.Activated += PowerupActivated;
        playerTwoPowerup.Deactivated += PowerupDeactivated;

        //JEP - moved from events since these only need set once
        activatedVec = new Vector2(100, 125);
        deactivatedVec = new Vector2(100, 150);
        powerupReady = false;

    }

```

# Answer
> 5 votes
You could pass your instance of GraphicsDevice as a parameter in the constructor of you GameplayScreen and set your global variable you have already declared as the value of your input parameter like so

```
    class GameplayScreen : GameScreen
    {
        ...
        private GraphicsDeviceManager graphics;

        public GameplayScreen(GraphicsDeviceManager graphicsDeviceManager)
        {
           this.graphics = graphicsDeviceManager;
           TransitionOnTime = TimeSpan.FromSeconds(1.5);
           TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }
        ...
    }

```

This is assuming however that you have access to your graphics device instance from where ever you are creating an instance of this class (I assume GameStateManagementGame)

# Answer
> 5 votes
First rather than doing the whole static Instance thing, pass (this) as a parameter when you create the HUD also you have a GraphicsDeviceManager in the GameScreen which isn't needed as you have a reference to the GameStatemanager which should also have a reference to a GraphicsDeviceManager.

but to answer you main query you access the GraphicsDevice by GraphicsDeviceManager.GraphicsDevice so from your GameplayScreen class it would be

```
graphics.GraphicsDevice

```

which isn't public atm :-)

# Answer
> 4 votes
ScreenManager has a reference to the Game, and Game has a reference to the GraphicsDevice. So:

```
GraphicsDevice gfx = ScreenManager.Game.GraphicsDevice;

```

# Answer
> 3 votes
You can always grab the graphics device from the Game class ... so as long as you have a reference to that you can do:

```
IGraphicsDeviceService graphicsservice = (IGraphicsDeviceService)Services.GetService( typeof(IGraphicsDeviceService) );

```

Reference here: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.services.aspx

# Answer
> 1 votes
I'm not sure ,but did you check for it in the ScreenManager? Some architectures for state management i used kept the graphics device reference in there .

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


# Question
Title: Facilitating XNA game deployments for non programmers
I'm currently working on an RPG, using the RPG starter kit from XNA as a base. (http://xbox.create.msdn.com/en-US/education/catalog/sample/roleplaying\_game) I'm working with a small team (two designers and one music/sound artist), but I'm the only programmer. Currently, we're working with the following (unsustainable) system: the team creates new pics/sounds to add to the game, or they modify existing sounds/pics, then they commit their work to a repository, where we keep a current build of everything. (Code, images, sound, etc.) Every day or so, I create a new installer, reflecting the new images, code changes, and sound, and everyone installs it.

My issue is this: I want to create a system where the rest of the team can replace the combat sounds, for instance, and they can immediately see the changes, without having to wait for me to build. The way XNA's setup, if I publish, it encodes all of the image and sound files, so the team can't "hot swap." I can set up Microsoft VS on everyone's machine and show them how to quickly publish, but I wanted to know if there was a simpler way of doing this.

Has anyone come up against this when working with teams using XNA?

# Answer
> 12 votes
First of all, I don't think you need to be publishing and creating an installer every time. Just build the project and place the output files (i.e. the EXE and the Content folder plus any DLL dependencies you might be using) in the repository, and it should run on their computer too, as long as they have the XNA redist installed.

As for your question, I can think of two solutions, one of which involves installing Visual Studio on their machines, and other involves making some changes to the game:

* Have them install Visual Studio and teach them to pass their assets through the XNA content pipeline. They just need to create a content pipeline project, drag the files there and build. Then they can swap the resulting XNB files with the ones in the project folder, and run the EXE to see the changes.
* If you're developing for Windows, you can change your code so that it loads assets at runtime in their original formats, without having to go through the content pipline. For loading images you could use `Texture2D.FromStream` (like this example) and for audio the best solution I've found was to use the FMOD API instead (like this example). Then they can just swap the assets directly and run the game.

To take things even further, you could also try to make your game as data-driven as possible. This basically means that everything in the game that you should be able to change easily, such as character class stats, or the path of the images and sound files you're using, should be taken out of the code and placed in external text files (e.g. XML, JSON, INI). Then you only need to edit those files in a text editor to see changes in the game, and there's no need to rebuild.

# Answer
> 4 votes
A little bit late to the party, but here is my idea.

I would go with the 3rd posibility which involves nothing like modifying the already existing code-base. This will work if, you will commit (and copy) the binaries (the actual game .exe and the associated .dlls from the compilation) somewhere in an output directory - for example with a post-build script. Onwards, I will assume we are talking about Visual Studio 2010 and XNA Game Studio 4.0 (The procedure is very similar for other versions, just need to replace some numbers)

So, the idea is: create a script (.cmd) in the root of your project, where the .sln solution resides, with the following steps:

1. Invoke the "Visual Studio 2010 Command Prompt":

> call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86

This is in order for our script to be able to find the XNA libraries, and all the required tools and binaries.
2. Call the MSBuild task on the Content Project (.contentproj):

> msbuild /property:XNAContentPipelineTargetPlatform=Windows /property:XNAContentPipelineTargetProfile=Reach mygame.content/projectfile.contentproj

You can modify the properties by specified different platforms/profiles. You can even go further to build the content for more platforms at a time (Windows Phone, Xbox 360 or Windows). The profile can be: Reach or HiDef (http://msdn.microsoft.com/en-us/library/ff604995.aspx)
3. Copy recursively the output to the folder where the binaries + actual game is stored on the repository:

> xcopy /d /y /i /e bin\x86\Debug\Content\* ..\game\_output\Content

For details on the flags, you can invoke in the command prompt: `xcopy /?`. The important ones are: `/d`, to copy only modified files - in case you have many assets it's useful not to copy over and over again the already existing and unmodified ones; `/y` for automatically overwriting existing files so they can be updated with a newer version. I've used `xcopy` because the normal `copy` can't copy recursively folders as far as I know - and probably you are structuring the content in folders and sub-folders. Plus, it's better than the normal `copy` (lots of different flags).
4. Call `pause` so the script will wait for user input. This is useful to check if the build was fine and no errors were encountered.

Now, the artists (or anyone) who modifies the content files, need just to double click the .cmd script and the new content will be built and copied to the output directory where the commited artifacts are, ready to be tested.

However, there is a small problem, for which you'll have to fallback to the 1st point of David's post: if the artists want to modify the Content project by adding/removing/moving around files, they have to do that by opening the project in Visual Studio (or editing the project file by hand, which I doubt anyone would do). Like I said, this is a small issue, because they could just commit the new files in the repository, and you, the coder will include them in the Content Project when the code is done to handle those.

On this idea, Shawn Hargreaveas posted something about msbuild and building the Content Projects from command line: Link His solution was to create a new file, but I think it's easier and more maintainable to use directly the already existing project file.

PS: Sorry for the long post xD

---
Tags: xna, rpg
---


# Question
Title: Placing items randomly in a dynamically generated terrain
I'm currently working on a 'Tiny wings' like game. I've already asked about the angle of the items in curved lines and i solved (thank you for responses),i'm currently placing the items in random positions, but the terrain it's dynamically and i don't get this working.

I've a vector with the points of the terrain, and i'm doing something similar to this (Iterating trough vector):

```
if( _SPManager && i % 15 == 0 && i != 0 )
{
    if (  _settings.specialPoints && _currentPoints < _settings.specialPoints )
    {
        _SPManager.addPoint( _hillsPosition[i].x , _hillsPosition[i].y );
        _currentPoints++;
    }
}

```

But it isn't working as i expected. It isn't displaying the right number of items (Always shows less than i specified).

How do i should place the items?

Thanks :)

# Answer
It is not clear from the code, what you are achieving by iterating. Could you do this instead:

```
//I am guessing:
//_settings.specialPoints == //wanted amount of items

var j : int = 0;
for(var i : int = 0; i < _settings.specialPoints; i++) //I'm assuming the above
{
    j = Math.floor(Math.random() * _hillsPosition.length);
    _SPManager.addPoint( _hillsPosition[j].x , _hillsPosition[j].y );
}

```

Will that work, again please clarify your goal and how the current code describes the steps to get it done. (add commenting) Thanks

Do you only want indexes that divide by 15 with no remainder for some reason?

```
//replace the earlier randomizer with this:
j = Math.floor(Math.random() * _hillsPosition.length); //same as before
j -= j%15;

```
> 0 votes

---
Tags: actionscript-3
---


# Question
Title: Rotate triangle so that its tip points in the direction of the point on the screen that we last touched
OpenGL ES - Android.

Hello all, I am unable to rotate the triangle accordingly in such a way that its tip always points to my finger.

What i did : Constructed a triangle in by GL.GL\_TRIANGLES. Added touch events to it. I can rotate the triangle along my Z-axis successfully. Even made the vector class for it.

What i need : Each time when I touch the screen, I want to rotate the triangle to face the touch point.

Need some help.

Here's what i implemented. I wonder that where i am going wrong?

My code :

```
public class Graphic2DTriangle {

private FloatBuffer vertexBuffer;
private ByteBuffer indexBuffer;

private float[] vertices = {

   -1.0f,-1.0f, 0.0f,
   2.0f, 0.0f, 0.0f,
   -1.0f, 1.0f, 0.0f
};

private byte[] indices = { 0, 1, 2 };

public Graphic2DTriangle() {
  ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
  vbb.order(ByteOrder.nativeOrder()); // Use native byte order
  vertexBuffer = vbb.asFloatBuffer(); // Convert byte buffer to float
  vertexBuffer.put(vertices);         // Copy data into buffer
  vertexBuffer.position(0);           // Rewind

  // Setup index-array buffer. Indices in byte.
  indexBuffer = ByteBuffer.allocateDirect(indices.length);
  indexBuffer.put(indices);
  indexBuffer.position(0);
}

public void draw(GL10 gl) {
  gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
  gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
  gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_BYTE, indexBuffer);
  gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
  }
}

```

My SurfaceView class where i've done some Touch Events.

```
public class BallThrowGLSurfaceView extends GLSurfaceView{

MySquareRender _renderObj;
View _viewObj;
float oldX,oldY,dX,dY;
final float TOUCH_SCALE_FACTOR = 0.6f;
Vector2 touchPos = new Vector2();
float angle=0;

public BallThrowGLSurfaceView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    _renderObj = new MySquareRender(context);
    this.setRenderer(_renderObj);
    this.setRenderMode(RENDERMODE_WHEN_DIRTY);

}

   public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
   touchPos.x = (2*event.getX())/getWidth()   -1.0f;
       touchPos.y = (2*event.getY())/getHeight()  -1.0f;
       Log.i("Co-ord", touchPos.x+"hh"+touchPos.y);
       switch(event.getAction()){
          case MotionEvent.ACTION_MOVE :

                _renderObj.mAngle = touchPos.angle() - 180;
                     requestRender();
                    Log.i("AngleCo-ord", _renderObj.mAngle +"hh");
                }
              oldX = touchPos.x;
              oldY = touchPos.y;
              Log.i("OldCo-ord", oldX+" hh "+oldY);
              return true;
        }

 }

```

Last but not the least. My vector2 class.

```
   public class Vector2 {
public static float TO_RADIANS = (1 / 180.0f) * (float) Math.PI;
public static float TO_DEGREES = (1 / (float) Math.PI) * 180;
public float x, y;

public Vector2() {
}

public Vector2(float x, float y) {
    this.x = x;
    this.y = y;
}

public Vector2(Vector2 other) {
    this.x = other.x;
    this.y = other.y;
}

public Vector2 cpy() {
    return new Vector2(x, y);
}

public Vector2 set(float x, float y) {
    this.x = x;
    this.y = y;
    return this;
}

public Vector2 set(Vector2 other) {
    this.x = other.x;
    this.y = other.y;
    return this;
}

public Vector2 add(float x, float y) {
    this.x += x;
    this.y += y;
    return this;
}

public Vector2 add(Vector2 other) {
    this.x += other.x;
    this.y += other.y;
    return this;
}

public Vector2 sub(float x, float y) {
    this.x -= x;
    this.y -= y;
    return this;
}

public Vector2 sub(Vector2 other) {
    this.x -= other.x;
    this.y -= other.y;
    return this;
}

public Vector2 mul(float scalar) {
    this.x *= scalar;
    this.y *= scalar;
    return this;
}

public float len() {
    return FloatMath.sqrt(x * x + y * y);
}

public Vector2 nor() {
    float len = len();
    if (len != 0) {
        this.x /= len;
        this.y /= len;
    }
    return this;
}

public float angle() {
    float angle = (float) Math.atan2(y, x) * TO_DEGREES;
    if (angle < 0)
        angle += 360;
    return angle;
}

public Vector2 rotate(float angle) {
    float rad = angle * TO_RADIANS;
    float cos = FloatMath.cos(rad);
    float sin = FloatMath.sin(rad);

    float newX = this.x * cos - this.y * sin;
    float newY = this.x * sin + this.y * cos;

    this.x = newX;
    this.y = newY;

    return this;
}

public float dist(Vector2 other) {
    float distX = this.x - other.x;
    float distY = this.y - other.y;
    return FloatMath.sqrt(distX * distX + distY * distY);
}

public float dist(float x, float y) {
    float distX = this.x - x;
    float distY = this.y - y;
    return FloatMath.sqrt(distX * distX + distY * distY);
}

public float distSquared(Vector2 other) {
    float distX = this.x - other.x;
    float distY = this.y - other.y;
    return distX * distX + distY * distY;
}

public float distSquared(float x, float y) {
    float distX = this.x - x;
    float distY = this.y - y;
    return distX * distX + distY * distY;
}
}

```

PS : Please see the image for better understanding.

# Answer
You can use atan2 to find the angle of rotation. If (tx, ty) is your touch coordinate and (x,y) is the center of your rotation you can call

```
double rot = Math.atan2(ty-y, tx-x); //first y then x

```

rot is an angle in radians \[-pi, pi\] just rotate your triangle using it

---

EDIT

Implementation.

Assuming that you have setted up opengl so that screen coordinates goes from \[-1, 1\] on both the axes, you need to scale the touch coordinates so that they match your opengl coordinates like this.

```
touchPos.x = (2*event.getX())/getWidth()  -1.f;
touchPos.y = (2*event.getY())/getHeight() -1.f;

```

From your code above I think that your center of rotation is (0,0,0) so you don't need to translate touchPos.

touchPos is a Vector2, your class already have an angle() method.

```
float angle = touchPos.angle() - 90;

```

I'm not really sure about -90 degrees here, don't have time to test the code so if the rotation is off of 90 degrees adjust this. I don't know how the rest of your code is implemented but probably you should edit your onTouchEvent and set

```
_renderObj.mAngle = angle;

```

Reassuming your should replace onTouchEvent with this

```
public boolean onTouchEvent(MotionEvent event) {
    touchPos.x = (2*event.getX())/getWidth()  -1.f;
    touchPos.y = (2*event.getY())/getHeight() -1.f;
    Log.i("Co-ord", touchPos.x+"hh"+touchPos.y);
    switch(event.getAction()){
    case MotionEvent.ACTION_MOVE:
        _renderObj.mAngle = touchPos.angle() - 90;
        requestRender();
        Log.i("AngleCo-ord", _renderObj.mAngle +"hh");
    }
    oldX = touchPos.x;
    oldY = touchPos.y;
    Log.i("OldCo-ord", oldX+" hh "+oldY);
    return true;
}

```
> 4 votes

---
Tags: android, opengl-es, rotation, vector, touch
---


title: Collision detection with curves

text:
# Question
Title: Collision detection with curves
I'm working on a 2D game in which I would like to do collision detection between a moving circle and some kind of static curves (maybe Bezier curves).

Currently my game features only straight lines as the static geometry and I'm doing the collision detection by calculating the distance from the circle to the lines, and projecting the circle out of the line in case the distance is less than the circles radius.

How can I do this kind of collision detection in a relative straightforward way? I know for instance that Box2D features collision detection with Bezier curves. I don't need a full featured collision detection mechanism, just something that can do what I've described.

---

UPDATE: Thanks a lot for the great answers! I'll have to read up on Bezier curves to fully understand the method you've described. Then I'll get back to you.

# Answer
> 6 votes
29/09/2012 - 23:20

I created a git Repo here: https://github.com/ArthurWulfWhite/Bezier-Distance/

You are welcome to download the source files as a zip from there. It also includes a demo you can compile using FlashDevelop. To use the demo, open the project in Flash Develop and click 'Test Project'. While running the demo, click the LMB to randomize a new Bezier curve and a new Circle.

Good luck!

The zip link is hard to see - just use Ctrl + F and type zip. This source represents a couple of weeks of reasearch and programming, I hope you enjoy it.

---

If you plan on dividing the bezier recursively into segments and checking for collisions with them, I suggest making a 100,100 array (grid) and placing each segment in the four nearest squares, so you only have to check for collisions with 4 / 10,000 of the segments each frame.

I do think you will benefit from box2d both as a programmer and as a game creator, since there are lots of hidden little hurdles in making a 'simple' physics engine that make the motion seem a little bumpy and less fluid then it could be.

Old answer: The pure way.

You can actually see if a circle is colliding with a Bezier curve, by checking the distance between the distance between the center of the circle and the closest point on the curve.

The equation for the distance (in general)

explained:

Bezier equation:

```
q(t) = (1-t) * ((1-t) * start.(x,y) + t * control.(x,y)) + t*(t * control.(x,y) + (1 - t) * end.(x,y))

```

This can be summed up to (with some algebra) - I will omit .(x,y) for readability (they are still points, not one number)

```
q(t) = (start -2 * cont + end) t^2 + (-2 * start + 2 * control) + start

```

The distance from point (x,y) is:

```
sqrt ((q(t).x - point.x)^2 + (q(t).y - point.y)^2)

```

To find the closest point on the bezier to the ball, you need to derive and find all the points where the derivative equals zero (the roots). It is a polynomial of the third degree so you could use a closed formula but it could be unreliable since the precision of the computer floating point represented fractions may not be sufficient. It is far better to use Newton or something of that nature.

The derivative you need to find the roots for is:

Assuming: a = start b = control c = end d = cirlce center point

The tricky part is multiplying this points, you have to use dot product.

*If you like, I have the code for this and I can share it here in the form of a function that simply returns a boolean if there is a collision or not and an angle of collision. Some problems could appear in naive implementation of a collision engine like this for instance a fast moving ball could get caught between two curves.*

I recommend avoiding it for now, just sum up the coefficients for the x axis and for the y axis and add them up.

The use any reliable method you may choose like Newton to find the roots, check the distance from the root points on the bezier, 0 \<= t \<= 1 to the circle center and check the distance for the two ends of the bezier (start and end) to the circle center, whichever one is closest, will tell you if there is a collision.

If the radius is smaller than the minimal distance, there is a collision.

The angle is approximately the one between the center of the circle and the closest point on the bezier.

That being said, if you truly wish to make a game with collision physics, I suggest you just iterate over the bezier

```
    q(t) = (1-t) * ((1-t) * start.(x,y) + t * control.(x,y)) + t*(t * control.(x,y) + (1 - t) * end.(x,y))

```

Divide each piece in the middle recursively until it is small enough, lets say 10 pixels or less, then build the bezier roughly from boxes and use **Box2d** for the physics cause it is possible that writing all this collision detection code will prove to be a great time sink that doesn't enhance the gameplay much. Using Box2d has proven itself in countless projects in the past.

# Answer
> 7 votes
To do this, I would :

* Break the bezier curve into severals line segments and store them.
* Put all these segments in a axis aligned bounding box for the whole curve.

Collision detection :

1) check if sphere is inside the main bounding box. if no, no collision.

2) otherwise, check if any of the individual segments calculated above collide with sphere. See Line–sphere intersection article from Wikipedia.

EDIT : if you need high precision and want good performance, you can also create a main bounding box for the whole curve, then subdivide the curve in two segments (eg : `[0.0 - 0.5]` and `[0.5 - 1.0]`). Create a bouding box for each of them, then again subdivide each of these segments in two segments (thus giving `[0 - 0.25]`, `[0.25 - 0.5]` and `[0.5 - 0.75]`, `[0.75 - 1.0]`). Continue like this until you reach enough precision. in the end you will have a `binary tree` of bounding boxes with main curve bounding box at root and line segments at the leaves. searching in in the tree will gave you `O(log n)` instead of `O(n)` (where `n` = number of line segments for the curve)

# Answer
> 5 votes
The intersection between a line and a Bezier curve is achieved mathematically by subdividing the curve. This means relying on the curve's convex hull property and dividing it into smaller arcs with different control polygons in a divide-et-impera-like fashion.

This article covers it upto a point: http://students.cs.byu.edu/~tom/557/text/cic.pdf.

The nice part is that the algorithm works with any line, you just have to apply a rigid transform to the curve so that you can consider your target line as being parallel to the Ox axis.

Similarly, you can check against the circle and the polygon of each such a bezier arc when you subdivide a Bezier arc into two sub-arcs. The circle should intersect the control polygon of an arc for a curve-to-circle test to make sense.

---
Tags: collision-detection, beziers
---


# Question
Title: How Would I create alternate players (Turn base Event)
The picture above shows 2 players. Each containing 3 characters. I want to know how to make a Turn based event starting with player 1 alternating turns with player 2. And in every alternation each character gets a turn. If a character dies, the next character on the same team goes, and so on.

How would I create this? Is there a tutorial? I haven't made any turn-based games so I don't know how to program these kinds of stuff.

# Answer
Assuming you have 2 players always, you'll then need, for each player:

* A list containing their characters
* A counter for which of their characters is currently active

As the players trade turns their character counter should go up until it hits it's maximum size (3?) and then start back over at 1. Should a character die, take appropriate action to keep the counter correct. This is something your overall game needs to keep track of, only changing after a turn has been completed.
> 1 votes

# Answer
I don't know Unity, so treat this as a pseudo-code:

```
var charList:Array = new Array ();

var continueLoop:Boolean = true;
for ( var i:int = 0; continueLoop; i++ ) {
   continueLoop = false;
   for each ( var p:Player in players ) {
      if ( p.units.length > i ) {
         charList.push ( p.units[i] );
         continueLoop = true;
      }
   }
}

```

Now divide the turn to `charList.length` number of rounds, and activate the `charList[current_round]` unit on beginning of every round. Sort player.units by unit speed, if you want to give them initiative in *Heroes of Might and Magic III* style.
> 1 votes

# Answer
You could simply queue the players in order and just dequeue the first in line. The trigger to add them to the queue totally depends on your system ( I think a state machine could be in order here ). For example; if your character order depend on various triggers like stats and timers. You should monitor their properties and add them to the queue if a certain conditions are met.

I can't really give you any specific code or an example because it's specific to your system obviously. Look up how queues work if you don't know them yet.
> 0 votes

---
Tags: unity, turn-based
---


title: 2D Magnet-like repelling behavior

text:
# Question
Title: 2D Magnet-like repelling behavior
If somebody wanted to develop a system between two intersecting rectangles so that the rectangles would, in a gradual process, push eachother away from one another until no longer intersecting, with the repelling force being stronger depending upon how deep the intersection is... what would the math look like?

# Answer
```
a:Object;
b:Object;

dx:Number = a.x - b.x; //distance by x
dy:Number = a.y - b.y;
distance:Number = Math.sqrt ( dx*dx + dy*dy );

```

If you want to simulate magnet behavior, you want to base forces on distance between them. Physics say so:

But you will be fine with:

```
force = Math.floor ( MAX_FORCE / distance );

```

And then you need to use trigonometry to apply force as velocity change:

```
var angle:Number = Math.Atan2 ( dy, dx );
var x_speed:Number = force * Math.cos ( angle );
var y_speed:Number = force * Math.sin ( angle );

a.vx += x_speed;
a.vy += y_speed;
b.vx -= x_speed;
b.vy -= y_speed;

//and of course a.x += a.vx etc.

```
> 13 votes

---
Tags: xna, 2d, xna-4.0, physics
---


# Question
Title: What happened to the Journal of Game Development?
The lengthy mission statement from its website states:

> The lack of game-specific research has prevented many in the academic community from embracing game development as a serious field of study. The Journal of Game Development (JOGD), however, provides a much-needed, peer-reviewed, medium of communication and the raison d'etre for serious academic research focused solely on game-related issues. The JOGD provides the vehicle for disseminating research and findings indigenous to the game development industry. It is an outlet for peer-reviewed research that will help validate the work and garner acceptance for the study of game development by the academic community. JOGD will serve both the game development industry and academic community by presenting leading-edge, original research, and theoretical underpinnings that detail the most recent findings in related academic disciplines, hardware, software, and technology that will directly affect the way games are conceived, developed, produced, and delivered.

The Journal of Game Development was established in 2003. It's hard to find any information about the issues but at four issues per year, I estimate the last issue was distributed sometime in 2005 or 2006. It had a good editorial board of college professors and a founding editor from Ubisoft. The list of articles looks good. The price was reasonable.

**So what happened to it?** Its website recently went down but you can see the last Archive.org version.

The editor-in-chief is a professor at my school so I intend to ask him in person in a week or two, but I thought I'd see what you might be able to dig up about it first. Of course I will be sure to add an answer with his official word on the matter at that time.

# Answer
I pitched the concept for the Journal of Game Development to Charles River Media after we'd seen success on a few of the Game Programming Gems books. At the time we were starting to see a surge in the number of schools offering game development courses, or at least interested in offering them. We couldn't find anywhere that professors at these institutions could successfully publish research and have it be considered an accredited journal that would contribute toward their tenure requirements. Of course there were venues like SIGCHI and SIGGRAPH, but nothing specifically game-focused, and both of those organizations were only slightly interested in game development at the time. So this was the idea for the journal, to be a place where valuable research could be published, that would be a resource for both students and professors -- a place that we could hopefully, ten years later, see the evolution of game development.

Unfortunately it was not to be. We needed the journal to publish a particular number of volumes per year for a few years in order for it to gain its status as an accredited journal. Between challenges getting institutions to purchase it, and challenges getting all of us who were so busy to focus on it, we had a difficult time keeping a consistent publishing pace. I'm sad about it in retrospect, as I still feel it would have been an exceedingly valuable resource, and the people working on it were a great team.
> 9 votes

# Answer
Unfortunately the publisher, Charles River Media, made a business decision to stop printing the journal.

However there are other, more area-specific journals for game development in existence (i.e. journals about AI, networking, etc. - one specific aspect of game development).
> 6 votes

---
Tags: books
---


# Question
Title: Is it unprofessional to leave game resources to the open eye?
I'm still having problems packing my resources, after going through complicated APIs and basically just zip files which are exhausting my brain, I thought I could also pack the game with the resources visible to the human eye, in a simple folder.

Would that be unprofessional? Personally, I've never even seen games do that, it would basically mean that the player could just edit whatever he wants in the game, like go in map1.txt and add an X somewhere to create a wall, or change the player sprite to a pony in MS PAINT.

# Answer
> 45 votes
No it isn't, changing the game data is called modding, which is a common practice and often seen as positive effect. It's actually good to keep the game data as transparent as possible, and editing it as hassle-free as possible. Even more so if you are choosing more "advanced" players as your target audience.

The reason why you won't find many AAA-games that use a plain folder structure for their data is that they use custom optimized archive formats to get improved loading times. The downside is the decreased transparency and the additional required tools in the toolchain. However, for smaller, or 2D, games these two things are usually more worth than the improved loading time.

Just make sure that what the people see is not just a huge mess :) put the files into a proper folder structure.

# Answer
> 16 votes
In addition to other answers, two important concerns you should consider:

**Spoiling surprises**
Say I'm halfway through the game and discover the "video" folder. Curious, I click on one, and happen to see the final cutscene of the game.

**Losing challenge**
Same scenario, but I find the saved game format has a value for "gold". I change it from 250 to 999999999, and it works. Suddenly your carefully crafted difficulty curve, maximising the fun of the game, is gone.

Both could cause someone to lose interest in the game, partially if not entirely. This could end up in a lower overall impression of how good the game was (unfair but true).

Think about these in terms of your target audience - younger players especially are susceptible to spoiling their own fun without really understanding that this is what they are doing.

Even if you want to encourage modding, you might still want to protect users from ruining their own experience with the game "by accident".

# Answer
> 15 votes
Perhaps unprofessional is the wrong word. It really depends on the game whether or not leaving files exposed is a Bad Thing.

For a simple singleplayer game, players and modders will love you. You would be giving them the ability to easily change your game and do what they want. And keep in mind, there will *always* be modders for a game, no matter how small the game is. Many gamers will feel slighted if modding is difficult, after all, they bought your game and they should be able to do whatever they want in it.

On the other hand, easily editing game assets is bad for a multiplayer game, as it is considered cheating. Malicious players can replace content to make enemies more noticeable, walls transparent, etc. Although your game code should really enforce that assets haven't been tampered with, the "asset package" approach has the benefit of helping to deter this activity (security through obscurity).

# Answer
> 11 votes
There is an easy fix for it.. You could simply batch rename the extensions in a command prompt using something like

```
rename *.txt *.map

```

And then place them in a \map folder

You can access a command prompt from windows running cmd

This will not stop modders who know they want to mod the game and will leave a less sloppy impression on people who just want to play the game without all the content hanging around.

Yes, it will still be editable.. People will just be less likely to notice it.

To answer Eric Robertson's comment

If you wish to properly hide the content of your game from players you could use RSA encryption on those text files and merge them into one text file while you are at it. This should not be too much trouble although I suspect it is way beyond overdoing it.

# Answer
> 3 votes
If it ever was unprofessional, it may not be anymore. Early on games used their own package-formats, primarily to preserve their intellectual property (IP).

You can overcome some limitations such as *fragmentation* and *unnecessary function-invocations* of the underlying native file-system, by packing all resources into a single archive. This makes fragmentation events less likely when deploying the package on the client's PC.
In the worst case scenario you might end up having tiny individual file-resources scattered around your hard-disk sectors. (With the arrival of SSD's this point is often rendered moot)

But all of these benefits can also be had with the free, (Unix) age old `.tar`archive format.

Additionally, by using your own package-format, you can overcome limitations such as the lack of versioning, file-hashes, encoding and pointers/links within files, to name but a few.

**Concluding**, I would argue for transparency in Indie-development, unless you explicitly need to protect your IP.

---

As for the great points raised by `MGOwen`: To prevent **Spoiling surprises** you can rename the file extension, change file attributes, use uncommon media formats, excise the media-header and store it elsewhere, etc... To prevent **Losing challenge** use a binary serialization writer to store your game's state, with additional encryption and decoy-variables if you must.

Disclaimer: I am not a game developer. Only regard this post as a starting point...

# Answer
> 1 votes
It's easy to fix & otherwise search indexing will find your finale videos, etc. So,

For data files: flip bits with xor

```
   realByte_cpp = readByte_cpp ^ 0x44; // xor

```

To hide "Gold: 250" from GREP.

Just encode with the same (random) xor value.

To keep scenes away from casual users, try this: Machinarium translated filenames so \videos became \0101 and all files then had an 8-binary-digit id followed by .101 to stop file associations.

---
Tags: c++, assets
---


# Question
Title: C# graph library to be used from Unity3D
I'm looking for a `C#` graph library to be used inside `Unity3D` script.

I'm **not** looking for pathfinding libraries (I know there are good one available).

I could consider using a path finding library only if it gives me direct access to underlying graph classes (I need nodes and edges, and classic graph algorithms)

The only product I've seen that seems intersting is QuickGraph.

I have the following question:

1. Is it possible to use `QuickGraph` inside Unity3d?
2. If yes. Is this a good idea? Does it have any drawbacks? Is it a quite fast and well written/supported library? Does anyone has ever used it?
3. Are available other `C#` graph library that can be easily integrated in `Unity3d`?

# Answer
> 1 votes
> I have to solve a few basic graph problems: find strongly connected components, find best traversal, etc. **Quickgraph is the sort of library I'm looking for but the binaries don't work with mono/unity**, I'm willing to try compiling it myself but if there's a better option out there I'd much rather start with that.

~ From the Unity forums

Suggestions were:

**EDIT**: Just found this. Looks like this guy was able to use QuickGraph with Unity, but he doesn't mention how he did it.

**Edit 2020:** Working QuickGraph core implementation with Unity based on .NET standard https://www.nuget.org/packages/QuikGraph

---
Tags: unity, graph
---


title: How to switch between views in android?

text:
# Question
Title: How to switch between views in android?
I've tried several methods to switch between two views in my program. I've tried creating a new thread then have the view run for 5 seconds before creating intent to start my main activity. This is the code snippet from the said view class:

```
mHelpThread =  new Thread(){
        @Override
        public void run(){

            try {
                synchronized(this){
                    // Wait given period of time or exit on touch
                    wait(5000);

                }
            }
            catch(InterruptedException ex){
            }

            finish();

            // Run next activity
            Intent intent = new Intent(Intent.ACTION_MAIN, null);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            //stop();
        }
    };

    mHelpThread.start();

```

I can access the said view without error but it doesn't disappear after 5 seconds nor did it switched to main view when I even utilized an onTouchEvent() to detect touch on the screen of which it should have automatically closed. I've also tried adding a button on the said view to manually switch to main view:

```
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.help);
    final HelpView helpView = this;
    final Button btnback = (Button) findViewById(R.id.back);
    btnback.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            Intent intent = new Intent(helpView, MainActivity.class);
            startActivity(intent);
        }
    });

}

```

These codes worked, though, for creating a launcher for my program. So I thought that it would work the same if I added an option for help/rules(for the game) that would switch to another view. I've only since started using eclipse for android so pardon my lack of knowledge. Here is also the snippet from my manifest:

```
<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="MainActivity"
        android:label="@string/title_activity_main">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
        <intent-filter></intent-filter>
    </activity>
    <activity android:name="SplashScreen"
              android:theme="@style/Theme.Transparent">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name="HelpView"
              android:theme="@style/Theme.Transparent">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
        <intent-filter></intent-filter>
    </activity>
</application>

```

# Answer
> 2 votes
Try:

```
// create an intent for a specific component - your main activity
// your activity need to be also described in your manifest xml
Intent intent = new Intent(SplashScreen.this, MainActivity.class);

// tell os to display new activity (which one is described in the intent)
startActivity(intent);

```

Edit: Added comments

---
Tags: android, view
---


# Question
Title: Is it possible to work with a dedicated server in XNA?
Hi I want to release my XNA game to the XBOX platform, but I'm worried about the networking limitations. Basically, I want to have a dedicated (authoritative) server, but it sounds like that is not possible.

Which is why I'm wondering about:

1. Using port 80 web calls to php-driven database
2. Using an xbox as a master-server (is that possible?)

I like the sound of #1, because I could write my own application to run on the xbox, and I would assume other users could connect to it similar to the p2p architecture. Anyone able to expand on theory #2 above? or #1 as worst-case scenario?

# Answer
A is not possible, you can only work within the XNA networking framework on the xbox. This means connecting to xboxes with identical games running.

Re. option B, the server. You would have login in your game that checked something like your gamer id/name and if it was you it'd run in server mode, otherwise run in client mode.

This is has been done before and is fairly unreliable and not recommended as other xboxes won't always be able to see you and you'd need to leave your server xbox running constantly.

You mention a P2P architecture, but also of using the an xbox as a server (and others a clients presumably). This is somewhat contradictory (to me).

Another limitation you'd have is there is a limit that 32 (i think) xboxes can connect to each other at once. So if you went down the server xbox route that's 31 players before others wouldn't be able to join your server.

XNA on the xbox really isn't geared for a persistent world, MMO-like game for the reasons above, but if you're intent on doing it good luck.
> 2 votes

---
Tags: xna, networking, xbox
---


# Question
Title: HLSL problem with divide by homogeneous component
When I try to divide my position.z by my position.w in HLSL I get as result always 1.0f or higher. Is this a common problem for some reason? When I divide my position.x or y by the w this works fine. But the divide for the z gives a wrong result. I use the view matrix for my camera and the projection matrix as i use it in the game because I want to create a depthmap from the cameraposition. Can anybody explain what I'm doing wrong? Do I need another view matrix?

# Answer
I found out my lookat in my view layed before the draw point of the model which had influence on my z value. Now i've put my lookat further away and get a good result.
> 1 votes

---
Tags: xna, hlsl
---


# Question
Title: how do I add development build number each time I compile and play?
I wanted each time I play my game, it will show in the console how many times you compiled or run the game. How do I do that?

# Answer
> 3 votes
Well the question really is how do you compile your game:

* If you just use `javac` in the console, make a batch file (in whatever batching language your OS supports, i.e. .bat file for windows, .sh file for Linux, etc) that before executing the compiling command (or after) will read the current build number from a text file, increment it and re-write it;
* If you use a project build tool such as Ant or Maven, you can configure them to automatically place the build number (and build date, etc) into a specified text file.

Finally, whatever your approach, make your application code read the values in that text file and display them somewhere.

---
Tags: java, slick
---


title: How to stop reducing life?

text:
# Question
Title: How to stop reducing life?
***CODE***

```
Input input = gc.getInput();
            int xpos = Mouse.getX();
            int ypos = Mouse.getY();
            emu = "Enemy Life : " + enemyLife;
            Life = "Your Life Is" + life;
            Mousepos = "X:" + xpos + "Y:" + ypos;
            //test
            test1 = "Test INT" + test1int;
            if(!repeatStop)
            {
                       //if this button is press, the damage will add up. When
                        //pressed fight, it would start reducing the enemy health.

            if(input.isKeyPressed(Input.KEY_1))
            {
                test1int += 1;
            }

            }
            if((xpos>1007 &xpos<1297)&&(ypos>881 && ypos<971))
            {
                            //Fight button
                if(Mouse.isButtonDown(0)){
                    finishTurn=true;
                }
            }
                  //fight has started
            if(finishTurn==true)
            {
                         //this would reduce the enemy life
                if(floodControl1==false)
                {
                enemyLife-=test1int;
                }
                           //PROBLEM: Does not stop reducing!

                           //the below code was not successful. It did not stop it //         from reducing further.
                if(test1int>10)
                {
                    floodControl1=true;
                }
            }

```

***QUESTION:*** Ok now, this is what is does. When I press the key, 1, it adds up the damage to the enemy. When I press fight, It will then start to reduce the enemy's health. Now my problem is, it kept on reducing and deducting it until negative! How do I deduct it to my desired damage (My desired damage is the one when press key 1)?

# Answer
Just make a global field that records the damage to be dealt (the value obtained when pressing one), then when you press left, before decrementing the life, deduct the amount to decrement it with from the damage to be dealt value and check if that damage to be dealt value is still positive. When it becomes negative that means you've dealt enough damage and you should stop.
> 3 votes

# Answer
Your will stop decrementing *enemyLife* when the *floodControl1* is set to *true* right?

And you do:

```
if(test1int>10)
{
    floodControl1=true;
}

```

*test1int* is incremented when you press the key *1*. I can't see how you initialize the *test1int* variable in your code but assuming the following:

* test1int = 0
* I press the key *1* less than 10 times (so the value of *test1int* will be lower than 10)
* I press the left click of the mouse

You will never stop decreasing your *enemyLife* variable since test1int \< 10.

Here is a more *natural* way to do what you want:

```
if (floodControl1==false) {
    if (enemyLife - test1int < 0) { //check if reducing the enemyLife will not make it negative
        //stop decreasing
        enemyLife = 0;
        floodControl1 = true;
    } else {
        //continue decreasing
        enemyLife -= test1int;
    }
}

```
> 1 votes

---
Tags: java, slick
---


# Question
Title: How can be data oriented programming applied for GUI system?
I've just learned basics of Data oriented programming design, but I'm not very familiar with that yet. I've also read Pitfalls of Object Oriented Programming GCAP 09. It seems that data oriented programming is much better idea for games, than OOP.

I'm just creating my own GUI system and it's completely OOP. I'm thinking if is data oriented programming design applicable for structured things like GUI.

The main problem I see is that every type widget has different data, so I can hardly group them into arrays. Also every type of widget renders differently so I still need to call virtual functions.

# Answer
First of all, like snake5 said, only use DOD when necessary. If your GUI code already works and takes only 1-5% execution time, don't even try to rewrite it. It's not worth it. If you haven't written most of it, you could consider it, but only if you have a really fancy UI that's going to take a lot of processing power. Or maybe you just feel like writing some code using DOD, in that case just go ahead and play with it.

Now to answer your question. Yes you're right, different widgets have different data and maybe they're rendered differently. Are they really that different though? I don't know the features you need for your UI, but I can imagine lots of components share a lot of data. Some examples:

* All widgets have a position and size (and bounding box)
* Buttons, checkboxes, textboxes, etc all listen to mouse events using the bounding box
* Images, buttons, labels can all have images to render
* Buttons, labels, textboxes, textfields etc all have to render text

I'm sure there are more similarities if you take some more time to think about it. So we've established similarities and if you look at the description above, you can see that each widget type is composed of several (let's call them) "components". Let's take a button for example, it consists of:

* Spatial element
* Text renderer
* Image renderer
* Mouse handler

While a textbox consists of:

* Spatial element
* Text renderer
* Mouse event listener
* Keyboard handler

So let's create a struct (or class) with the data for each component. For instance:

```
struct Spatial {
    vector2 position;
    vector2 size;
    float depth;
    rectangle boundingBox;
    bool dirty; //set to true when pos or size is changed, calculates bBox again
}

```

Then, create a manager for Spatial. The manager has a flat list of Spatial structs, and when update is called it will go through all of them and update the boundingBox if dirty is true Do the same for each of the other components. TextRenderer updates and renders text on the screen, MouseHandler can call button callbacks or set checkbox state or determine which element has focus. KeyboardHandler updates the text of a textfield if it has focus.

Now, when we want to add a button, we don't actually add a button, but a set of components to the respective managers. The last thing we need is a UIElement class which has pointers/indices of all the components in the different handlers, so we can find them back, for instance when we want to delete it, or when one component needs info from another component.

So there you have the pitfall of OOP. You think of widgets as an object. Therefore, you naturally come to the conclusion that it's full of unique data and needs a class hierarchy and virtual functions. When you take DOD, you look at the data and you immediately notice the similarities between the widget's data and functionality. By splitting the UI elements into separate components, you can now update these components in batches, which improves things like cache utilization. Another advantage, you've made the codebase a whole lot easier to read. Instead of spreading (and sometimes even duplicating) code over a whole hierarchy of widget classes and subclasses, code is now located in a component that simply does what the name implies.

Now before I leave it at this, a few disclaimers. Let's start with the fact that I just thought this system up while writing. So there is loooots of room for improvement here. Take your time when you create your own system and think things through before you create something. Another thing to note is that I have no idea if my system is that much faster than a OO-based UI system. It depends (as always) on the data, how much there is and what usage patterns there are. Maybe OO is faster in your case. Maybe a hybrid approach works best. I don't know :) My idea is just a simple example of how you can apply DOD principles to what may seem like a perfect example for OOP at first sight.

One last thing, I don't want to take credit for the approach above. It is heavily based on component systems, which are used in lots of games and have been developed by people a lot smarter than I am. If you want to read more about it, there is a lot of info to be found just on google (just search "game component system") or on Stack Exchange.
> 4 votes

# Answer
Everything depends on (the amount of) data. If you need thousands of UI controls for some reason, it will become very applicable to nearly every part of a GUI system. If all you need is a few windows and buttons, my only advice would be "keep it simple".

P.S. It's not about "structured things vs. arrays" or something like that. It is about designing data and algorithms to work well together. And if OOP weren't so popular, DOD would just be labeled "common sense".

Some stuff for reading about DOD:

There are more publications about this but I picked these two as a good introduction to things. Most of the others were focusing on the heavy stuff that requires some assembly & profiling knowledge.
> 6 votes

# Answer
GUIs tend to be messy and look like Spaghetti Code. Using Model–view–controller with Mediator pattern can help. If your data is in a database, take a look at data binding.
> 0 votes

---
Tags: software-engineering, design-patterns, gui, data-oriented
---


# Question
Title: How to decide how much to charge for development?
So two other friends and I are a very small game dev studio. So far we haven't released a game but we have 2 games almost ready to launch. A bigger studio saw our work and now they want to work with us; they need people to develop mobile games for them (iOS, Android).

They want us to set the price for the projects (can't tell the specifics we signed a NDA). They will give us all the assets (graphics/sound) so we only have to code. And because they only work with Unity3D we have to learn it.

How do we decide how much to charge for the projects?

# Answer
> 14 votes
The best short answer I can give you is:

```
T = guesstimate how long it is going to take.
M = Check what is the average monthly pay for a programmer in your country.
P = Amount of people on your team.

```

Your offer to them should be:

```
T * P * M * 3

```

This advice of course is not offered as professional counseling and not intended to replace it.

They will likely try to negotiate for a better deal. Stick to the price as much as possible, nobody loves your better in the business world for being a flimsy negotiator.

After your first project when you see how much your earned you can start to adjust the prices for future projects accordingly.

# Answer
> 5 votes
The answer to this will vary wildly, but it's going to be based on a similar process for everyone.

Estimate how long the project will take, both in terms of person-hours spent coding and in terms of calendar days spent on the project. Now figure out about how much you want to be paid per hour and/or how much you want to earn over that span of dates.

EDIT: Make sure to include fixed costs like the cost of Unity Pro licenses! For a three-person team, the $3000 or so per person will be notable.

You may be talking about a fixed price or hourly rate (as ashes999 said, fixed-price is more attractive to the client), but in either case you'll be basing it on the above calculation.

They already want to work with you. Don't be afraid to explain that you're inexperienced with the pricing stuff. If you're willing to be flexible, they're likely to be forgiving about a number they can't work with.

Finally, don't be afraid to walk away! If they will only accept a number that's too low for you, move on without burning bridges.

# Answer
> 1 votes
For my experience this is a fake question, it's not a real question and it's more like a start for a trade, you can set whatever price you want to set but they will always drag you into a trading discussion.

My suggestion is since any price is going to be subject to their approval, think about this as the how much this is goind to cost for you and what is your expectation about how much you are going to earn from this: cost + expected earnings = base price .

Since you are most likely to have a discussion with this people is better for you to have clear in mind the lowest price possible that can be a reward for you and just go for the highest price that they will accept.

Consider the time spended with Unity as a big cost, this will be not so easy, also consider the possible legal issues that comes with a third part closed source game engine.

---
Tags: android, ios, sales
---


title: Animation with non-uniform frame sizes

text:
# Question
Title: Animation with non-uniform frame sizes
How do you know when to draw the next frame if its bounding box is larger/smaller than the current? For example, in KOF, some characters have elastic arms and things of the like..How are these handled in a game?

# Answer
> 2 votes
You know those paper dolls with moving arms? The arms are attached to the doll using tacks or something similar. What you're looking for is basically the virtual counterpart to this.

To have complete freedom between the sprite frames and their sizes, each part has to have a reference points (both from and to).

# Answer
> 2 votes
You would want to set up a definition of a `Frame` class which describes the position and dimensions of a single frame (independent of an actual image), a `FrameSet` class which has a name and a series of `Frames` to iterate over (again, independent of an catual image), and a `Animation` class that has a name, a `FrameSet`, the ability to iterate through the `FrameSets`, and a target spritesheet. When an `Animation` is called by name it blits from the spritesheet at the location described by the current `frame` in the current `frameset` with dimensions equal to the current `frame`.

# Answer
> 2 votes
Lets take Dhalsim for example, classic and answers your category of stretchy limbs. This is how it is done: http://sfgalleries.wikia.com/wiki/Sprite\_Sheets#Dhalsim

The artists, draws the sprite frames and places them on a sheet with enough room so that each frame has it's own rectangle. In another layer, the artist marks the center of mass of the character in each frame (so that the frames are in-synch during animation)

Another person, usually not an artist, uses a tool to save the positions of these rectangles mentioned above and their width and height.

If you require more detail on how to implement the tool that helps extract the rectangles and save them to xml or text format ask and I could elaborate.

How to write a tool to collect data for a sprite sheet:

1. Display the sprite-sheet(I assume you have that covered)
2. Allow moving(arrow keys or wasd) the image on (x,y) while retaining the offset -\> offset.x, offset.y (the offset is the (x,y) of top left corner pixel currently displayed)
3. Allow zooming in and out (+, -) 2x / 4x / 8x/ with two keys -\> zoom

point is (x,y)

rect is (x,y,width,height,label,index);

pseudo code main loop:

```
If(userClickedMouse()) {
    if(point1 == null)
        point1 = new Point();
        point1.x = offset.x + mouse.x/zoom;
        point1.y = offset.y + mouse.y/zoom;
    else
    {
        point2 = new Point();
        point2.x = offset.x + mouse.x/zoom;
        point2.y = offset.y + mouse.y/zoom;
        //prompt user to enter frame label and number//
        rects.push( Math.min(point1.x, point2.x),
                    Math.min(point1.y, point2.y),
                    Math.abs(point1.x - point2.x),
                    Math.abs(point1.y - point2.y)
                    label, index));
        //The rect is just an array a struct (x,y,width,height) values over and over - you can also use a struct (but I would just use integers)
        point1 = null;
        point2 = null;
    }
}

if (point1 != null) //display a rectangle describing the currently selected area.

```

If this makes sense let me know or please feel welcome to ask for elaboration.

To pick the frames 'character centering point' use a similar loop, that only asks the user to input one point.

Alternative:

Have the artist add this one pixel points in a new layer in Gimp/Photoshop and write a tool that opens the point layer and extracts their coordinates by iterating on all pixels and saves the results into your the format your prefer.

If you do it that way, you could easily calculate which point belongs in each rectangle and then pair them automatically.

---
Tags: animation, sprites
---