# Question
Title: Is there any "object" in monogame for windows phone 8, that is similar to Toast in Android?
The title pretty much sums it all.

Is there any "object" in monogame for windows phone 8 (for monogame to be exact), that is similar to Toast in Android?

My purpose is to give a notification / hint at what user do, until certain period / until next user input.

For example: If the player tapped "attack", then there is text shown "Select your target" in either top or bottom screen. Just like Toast in android.

Note 1 : I can do it manually, but i'm just curious. If I can use a pre-made function (such as Toast) it'll be simpler to implement, rather than making it myself.

Note 2 : Mine is a turn based tactic game (such as FF Tactic)

Thank you.

# Answer
Windows Phone has integrated functionality for displaying toast notifications: http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj662938(v=vs.105).aspx

But I don't think it's what you are looking for, since they always appear in the top part of the screen and are meant for showing notifications when the app isn't active.
> 1 votes

---
Tags: android, monogame, windows-phone-8
---


# Question
Title: Reducing overdraw cost: does triangle ordering matter?
I'm working on a project with procedural geometry, and will potentially have lots of opaque faces overlapping within the same model. Imagine an onion's layers. My understanding is it is better to draw the outermost layers first so inner layers' pixels can be discarded quickly by z-buffer test. If so, does that mean I should put the outermost triangles first in the index buffer for the best performance?

For reference, I'm using Unity.

# Answer
In theory draw order only matters when using multiple draw calls. Since video cards have a parallel architecture for vertex and fragment processing, the rendering order inside of a given mesh is non-deterministic. Of course this means that your method may work on some or even all of your target devices, but trusting undocumented and somewhat random features is usually a bad idea.

So you basically have to make a choice between multiple draw calls or some overdraw.

However you may not have to worry about it - even mobile graphics cards can render way more than you would expect nowadays. Some mobile architectures like PowerVR even have special handling for this exact case to reduce the overhead.

You can also try only rendering part of the mesh via occlusion culling or some other method, while having Unity's static batching enabled. But usually heavy premature optimization is a bad idea.
> 3 votes

# Answer
Generally there are two factors which you can reduce by Z-ordering your geometry:

1. Fragment calculations: If your setup supports Early-Z the GPU will perform a depthbuffer test right before the fragments shader is executed and thus avoid all the calculations if the fragment fails the test
2. Fillrate reduction: Fillrate is basically how much memory you write into your screen-buffer. Fillrate can become a major performance problem if it's very high.

So should you do it or not? First of all, you can do it, it shouldn´t hurt and if you can do it without spending much time on it, why not? If it will cost alot of time though you might be better of if you don´t do it at first. Later when you test your game and you run into performance problems you should figure out what causes those problems and eliminate them by optimising those sections. That´s the point where you might figure out that the Fragment shading of your procedural geometry is too expensive or your fillrate is too high and that´s when it becomes nececesary to do that kind of optimisation.

Hope this helps!
> 1 votes

---
Tags: rendering, performance, procedural-generation
---


title: Movement on Multiplayer Games

text:
# Question
Title: Movement on Multiplayer Games
I'm developing a JavaScript Multiplayer Game (Using NodeJS and Socket.IO). The problem I'm having is, on a Player's movement, the Event with the X and Y positions is sent to the server and then to all the other Players on that Server. Now, on a 60 FPS Machine, the event is sent to the server 60 times a second, resulting on smooth movement on all other Machines with 60 FPS. However, on a 30 FPS Machine, it's only sent 30 times a second, resulting on jumpy movement on higher FPS Machines (E.g. 60 FPS).

Is there any way to resolve this problem?

Thanks!

# Answer
> 5 votes
* Render loop, network traffic, and update loop should *always* be decoupled.
* Look into the publish/subscribe model.
* Your game probably has 'levels' (even 'the entire world' could be a level')
* Treat each level like a 'channel' (think IRC #channel, Twitter #topic, etc)
* When a user enters a level, they subscribe to that level's channel. Similarly, when they leave the level (log out, move out of range, etc) they unsubcribe from that channel.
* When a user performs an action warranting notification to other players, he sends a publish to his level#channel indicating his intent.
* If the server OK's the movement, the server then broadcasts to all players within the moving player's subscribed channel of the movement and/or new position.
* Each player subscribed to level#channel gets the update on the object in question, and makes the position change.
* When the render loop (separate from your network loop) draws everything, moved objects will have updated positions, and will appear to have moved.

# Answer
> 0 votes
You should interpolate the positions and rotations and possible other stuff on the client side and you should send data to the server/from the server at a fixed rate, 16-30 updates per second is fairly enought.

Besides that, your client should never send any position/speed information to the server because this would allow the players to cheat very effectivly. Remember that the server have to be always the authority.

---
Tags: javascript, html5
---


# Question
Title: How to simulate the movement of a ball in 2D due to force, gravity, and friction with surface?
I have a ball which I kick with some force. It has a starting x,y position, sat (2,3) and an intended target x,y say (7,8) position. That means I have to translate by (7-2, 8-3) i.e. 5 x units and 5 y units to reach destination.

The things acting on this ball are

force of kick(in direction of target), gravitational pull towards floor due to mass, and friction force provided by grass.

I will experiment different values of the 3 and see which one best simulates. But how do I calculate time required to destination and how much to translate in every frame of my game?

Can anybody please give me an equation for displacement due to these 3 factors and how velocity and other factors required in the equation change with time elapsed?

# Answer
> 1 votes
The ball has a kinetic energy of: when kicked.

The force pushing the ball down to the ground can be ignored, since a ball is round, it rolls (doesn't slide), so there's no static friction.

The force of the grass cannot be ignored. And, in this case, essentially acts like static friction, like a block sliding on the ground would encounter friction from the floor, a ball rolling on the grass encounters friction from the grass. We want to know how far the ball will go. Which means we want to know when the kinetic energy of the ball is zero. We want the amount of work done to negate the kinetic energy of the ball we found in the first equation (so we set our equation equal to the negated amount and solve). The amount of work done by friction to stop the ball can be found with:

Solving for distance gives us:

Now that you have the distance, the time can be found with this answer.

However, there are a few options for simulating the movement of the ball in game. One of them could easily lead to you not getting the distance defined by the formula above.

If you're simulating the physics with an iterative approach, your final result will be different (unless your time step is crazy small, you'll have large enough errors to notice). This is similar to the differences you'd get in a Riemann sum estimation vs integration.

An iterative approach is very common in games. But if you're looking for accuracy, you can use the physics equations above and calculate the position of the ball based on the time since the simulation started. The equations for calculating the position since the start of the simulation can be the equations for constant linear acceleration. Since the forces acting on the ball are constant throughout (friction of the grass).

---
Tags: 2d, physics, motion
---


# Question
Title: How do you programmatically generate a sphere?
Could someone please explain how it would be possible to create a sphere vertices, indices and texture coordinates? There is a surprising lack of documentation on how to do so and it is something that I am interested in learning.

I have tried the obvious, googling, looking on gamedev.net, etc. However, nothing covers the generations of spherical points, indexing them, and texturing.

# Answer
There are two general approaches:

The leftmost is termed the uv-sphere and the rightmost an icosphere.

GLUT tends to use the uv approach: look at the function `glutSolidSphere()` in the freeglut sourcecode.

Here is an excellent article on producing an icosphere: http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html

> The uv-sphere looks like a globe. For many purposes it is perfectly fine, but for some use cases, e.g. if you want to deform the sphere, it is disadvantageous that the density of vertices is greater around the poles. Here the icosphere is better, its vertices are distributed evenly.

You may also find this interesting: http://kiwi.atmos.colostate.edu/BUGS/geodesic/text.html it describes an approach to organising the faces into zones.

http://vterrain.org/Textures/spherical.html gives an excellent description of how you might choose to texture them.
> 36 votes

# Answer
There are 2 ways to do it:

1. Walk theta and phi in spherical coordinates, generate faces and tris
2. Create an icosahedron and recursively subdivide faces until desired tessellation reached.

## Sphere using spherical coordinates walk

For the first way, you just use a double nested for to walk theta and phi. As you walk theta and phi, you spin triangles to create your sphere.

The code that does it will look something like this:

```
for( int t = 0 ; t < stacks ; t++ ) // stacks are ELEVATION so they count theta
{
  real theta1 = ( (real)(t)/stacks )*PI ;
  real theta2 = ( (real)(t+1)/stacks )*PI ;

  for( int p = 0 ; p < slices ; p++ ) // slices are ORANGE SLICES so the count azimuth
  {
    real phi1 = ( (real)(p)/slices )*2*PI ; // azimuth goes around 0 .. 2*PI
    real phi2 = ( (real)(p+1)/slices )*2*PI ;

    //phi2   phi1
    // |      |
    // 2------1 -- theta1
    // |\ _   |
    // |    \ |
    // 3------4 -- theta2
    //

    //vertex1 = vertex on a sphere of radius r at spherical coords theta1, phi1
    //vertex2 = vertex on a sphere of radius r at spherical coords theta1, phi2
    //vertex3 = vertex on a sphere of radius r at spherical coords theta2, phi2
    //vertex4 = vertex on a sphere of radius r at spherical coords theta2, phi1

    // facing out
    if( t == 0 ) // top cap
      mesh->addTri( vertex1, vertex3, vertex4 ) ; //t1p1, t2p2, t2p1
    else if( t + 1 == stacks ) //end cap
      mesh->addTri( vertex3, vertex1, vertex2 ) ; //t2p2, t1p1, t1p2
    else
    {
      // body, facing OUT:
      mesh->addTri( vertex1, vertex2, vertex4 ) ;
      mesh->addTri( vertex2, vertex3, vertex4 ) ;
    }
  }
}

```

So note above, its important to wind the top cap and bottom cap using only tris, not quads.

## Icosahedral sphere

TO use an icosahedron, you just generate the points of the icosahedron and then wind up triangles from it. The vertices of an icosahedron sitting at the origin are:

```
(0, ±1, ±φ)
(±1, ±φ, 0)
(±φ, 0, ±1)
where φ = (1 + √5) / 2

```

You then have to just look at a diagram of an icosahedron and wind faces from those verts. I already have code that does it here.
> 10 votes

# Answer
If the points don't have to be locally uniform, but should be globally uniform, and don't have to follow any set pattern, you can use a variant of dart-throwing algorithm to distribute *n* points on a sphere with radius *r*, on average *dist* points apart. These values are then roughly:

1. If you want to have a specific amount of vertices:
    * *n* = (desired amount of vertices)
    * *dist* = 2 × *r* × √(*π* / *n*)
2. If you want to have a specific average distance between the vertices:
    * *n* = 4 × *π* × (*r* / *dist*)2
    * *dist* = (desired average distance)

In the simplest case, you can then uniformly pick points at random by picking two uniformly distributed variables *u* and *v* from (0, 1) and calculating the polar coordinates from them according to the formulas *θ* = 2 × *π* × *u* and *ϕ* = arc cos (2 × *v* \- 1); then dismissing any points which lie too near to the already picked points. For a slightly more complex and significantly better-performing algorithm, see "Dart Throwing on Surfaces" by Cline, Jeschke, White, Razdan and Wonka.

After you picked your first four points (assuming no three of them are *degenerate*, that is - they don't lie on the same great circle, but that's highly unlikely), you can create four faces between them, and each time you add a new point, you can split the face it belongs to accordingly into three sub-faces.

For texturing purposes you can then map the points to a cube map.
> 3 votes

---
Tags: rendering, geometry, procedural-generation
---


# Question
Title: How do I calculate speed given x y components of a velocity vector?
I have some code that returns the x and y linear velocities of a moving space ship. How can I combine these to give me total speed?

```
x = self.player._box2dBody.GetLinearVelocity().x;
y = self.player._box2dBody.GetLinearVelocity().y;

```

So if:
x = 1.99
y = -1.63

How do I calculate the total speed?

# Answer
> 9 votes
In this situation, the length of the vector would be considered the speed, since the vector itself represents the velocity (speed and direction). This is also referred to as the magnitude. The vector class you're getting `.x` and `.y` from likely already has a built in implementation for getting the magnitude or length.

Where is the magnitude of the vector.

I suggest you read up on linear algebra. Wolfire has put together a nice series of blog posts on the topic that should get you up to speed on the basics.

# Answer
> 5 votes
Do you remember this from early high school math?

The length of the blue side is 3.
The length of the green side is 4,
And thus the length of the red side is SQRT( 32 \+ 42 )

Imagine that the green line is the X-speed and the blue line is the Y-speed.

---

Having said that, yes, so read up on some math. It will come in quite handy and Byte56's answer does cover that. I just posted this to add an easier version.

---
Tags: physics, vector, linear-algebra
---


title: Optimization Question about Singleton

text:
# Question
Title: Optimization Question about Singleton
I am using Unity with c#. I have two objects and one needs to call a function from the other which is a Singleton. For this I have two solutions. But what's the best thing to do :
\- Call for :
`MyScript.Instance.MyFunc();`
\- Store my Singleton object in my calling object and call it like this :
`myScript.MyFunc();`

What is the best thing to do in term of performance and optimizations.

Thanks a lot.

# Answer
> 2 votes
In Unity things are a bit different, usually this is what I go for when using the singleton design pattern:

1. Static class (`MyClass.Foo();`) - Used when creating non-Unity related, static functions. A good example would be a static data manager class that stores information about your player throughout the various scenes.
2. Mono/Singleton class inheritence (`MyClass.Instance.Foo();`) - Used when creating a static class that lives in the "Unity lifecycle", for example when you want to use MonoBehaviour's event functions (Update, Awake, etc) or using Unity's coroutines, etc. I've written a short blog post about my custom modified MonoSingletone which can also live through scenes: http://gamedevrant.blogspot.co.il/2013/07/unity-and-singleton-design-pattern.html

Regarding performance, both classes can easily work and get called hundreds of time per frame even on mobile devices - so it's definitely a question of the right tool for your specific problem.

---
Tags: c#, unity, performance, optimization
---


title: Tangent basis calculation problem

text:
# Question
Title: Tangent basis calculation problem
I have the problem with seams with calculating a tangent basis in my application.

I'm using a seems to be right algorithm, but it gives wrong result on the seams. What am I doing wrong? Is there a problem with an algorithm, or with the model? The designer says that our models with our normal maps are rendered correctly in Xoliul Shader Plugin in 3Ds Max, so there should be a way to calculate correct tangent basis programmatically.

Here's an example of the problem I'm talking about.

Steps, I've already taken:
\- Tried different algorithm (from Gamasutra, I can't post the link because I don't have enough reputation yet). I got wrong, much worse, results;
\- Tried to average basis vectors for vertexes are used in multiple faces;
\- Tried to average basis vectors for vertexes that have same world coordinates (this would be obviously wrong solution, but I've tried it anyway).

# Answer
Unfortunately, there is no really standard way to handle seams when generating tangent bases, and different applications do different things. If the method used in the engine differs from that used by the baking tool then you'll get problems like this.

The way I've solved this type of issue in the past is to use xNormal for normal map baking, as it lets you write a plugin in C++ to provide the tangent basis, and you can make sure to do it the same way you do in the engine. That should eliminate any issues with the seams.

I'm not familiar with the Xoliul Shader Plugin, but if it offers a way to specify your own tangents or export the tangents it's using, that should also enable you to get the tangents matched between the tool and the engine.
> 2 votes

---
Tags: 3d, algorithm, graphics-programming
---


title: What is this alpha blending result?

text:
# Question
Title: What is this alpha blending result?
I'm having an exam soon and got a problem with one alpha blending exercise:

```
BlendState BS3 {
    BlendEnable[0]     = TRUE;
    SrcBlend[0]        = ONE;
    SrcBlendAlpha[0]   = ZERO;
    DestBlend[0]       = ONE;
    DestBlendAlpha[0]  = ZERO;
    BlendOp[0]         = ADD;
};

```

There are 3 triangles overlapping `#1`, `#2` and `#3`. Each one has it's own RGBA values. The background color is `0.0, 0.0, 0.0, 0.0`.

My tries:

> SrcBlendAlpha and DestBlendAlpha are both 0.0. I can calculate all rgb values with
>
> 1\*rgb#3 + 1\*rgb#2 + 1\*rgb#3
>
> The alpha value is: 0 * alpha#3 + 0 * alpha#2 + 0 * alpha#1 = 0.0
>
> The resulting color then is: (0.0, 0.0, 0.0, 0.0)

Is my approach correct? Does this even make sense having a color with alpha value 0?

# Answer
With the introduction of programmable blending units, the intuitive meaning of alpha being a measure of opaqueness doesn't always hold.

In the two-operand blend you have two contributing fragments:

* the source (what you're blending, the new fragment),
* the destination (what already exists in the spot you're blending to).

You have two independent blending equations, one for the colour components and one for the alpha. Your blend state controls parameters of those equations, relating the two inputs with the output.

```
result.rgb = ColorBlendOp(src.rgb * SrcBlendColor, dst.rgb * DestBlendColor);
result.a   = AlphaBlendOp(src.a   * SrcBlendAlpha, dst.a   * DestBlendAlpha);

```

The blend operations are normally mathematical operations like add, subtract, reverse subtract, multiply, applying the operation to the two operands.

Your blend factors expands to constants or values related to the components of the source and destination fragments:

* `ONE` and `ZERO` expand to literal `1` and `0`.
* `SRC_ALPHA` expands to `(src.a)`.
* `INV_SRC_ALPHA` expands to `(1-src.a)`.
* `DST_ALPHA` expands to `(dst.a)`.
* And so on...

In order to evaluate a blending equation, substitute the blend factors and operations with their mathematical expansion, plug in the values from your source and destination fragments, and evaluate the expression.

At no point here do we attach any particular meaning to alpha and the colour components, they're just constants in an equation. The interpretation of the resulting RGB+alpha is up to the application, not the blender.

For your set of parameters, we get the following equation pair (assuming alpha blending uses the same operation):

```
result.rgb = Add(src.rgb * 1, dst.rgb * 1);
result.a   = Add(src.a   * 0, dst.a   * 0);

```

If you've got several blends to perform after each other, take the `rgb` and `a` of the previous expression and use it as destination `rgb` and `a` after each blend.

For an example of two things blended in turn onto a background, you've got:

```
final = blend(#2, blend(#1, background)))

```

or more explicit:

```
inter = blend(#1, background)
final = blend(#2, inter)

```
> 5 votes

---
Tags: c++, hlsl, blending, alpha-blending
---


# Question
Title: How to set multiple animations in cocos2d-x
I'm currently starting with cocos2d-x to build games for blackberry/android/iOS.

I have the png and plist for the animations of a character created with texturepacker. I load them with `CCSpriteBatchNode` and `CCSpriteFrameCache` then I use a function created by me that loads all frames into an array of frames, then create a `CCAnimation` object and store the `CCAnimate` object created with the animation (code is more clear) the thing is that I have a function that detect touches and it is supposed to cycle through all animations, but it always crashes.

here is some code (this goes in the `init()`):

```
_batchNode = CCSpriteBatchNode::create("Character/girl.png");
_cache = CCSpriteFrameCache::sharedSpriteFrameCache();

_cache->addSpriteFramesWithFile("Personajes/girl.plist");

_character = CCSprite::createWithSpriteFrameName("girlneutral1.png");
_character->setPosition(ccp(winSize.width * 0.1, winSize.height * 0.5));
_batchNode->addChild(_character, 1);
this->addChild(_batchNode);
createAnimation(0, "girlpush", 8, 0.15f);
createAnimation(1, "girlneutral", 4, 0.3f);
createAnimation(2, "girlcrash", 12, 0.3f);
createAnimation(3, "girljump", 12, 0.2f);
createAnimation(4, "girltrick", 12, 0.3f);

_character->runAction(CCRepeatForever::create( _charanimation[3]));

this->setTouchEnabled(true);

```

the function that loads the animations (\_charanimation\[\] is just an array of CCAnimate):

```
void HelloWorld::createAnimation(int a, CCString animation_name, int frames, float delay)
{
    CCArray* animframes = CCArray::createWithCapacity(frames);
    char str[100] = {0};
    for(int i = 1; i <= frames; i++)
    {
        sprintf(str, "%s%d.png", animation_name.getCString(), i);
        CCSpriteFrame* frame = _cache->spriteFrameByName( str );
        animframes->addObject(frame);
    }
    _charanimation[a] = CCAnimate::create(CCAnimation::createWithSpriteFrames(animframes, delay));
    //_charanimation[a]->getAnimation()->setLoops(-1);
}

```

and I get the animation to work (the one I set with `runAction()`) but if I try to change the animation, for example, when I touch the screen:

```
void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event)
{
    action++;
    action%=5;
    _character->stopAllActions();
    _character->runAction( CCRepeatForever::create(_charanimation[action]));
    char str[100];
    sprintf(str, "Animation: %d", action);
    pLabel->setString(str);

}

```

it crashes... I don't know if I am doing it wrong, if anyone could help, I will appreciate.

If I change the animation in `runAction()` it shows the animation correctly, but I can't change ingame with touches.

by the way, this is the error I get in console:

```
cocos2d-x debug info Assert failed: reference count should greater than 0
In function retain -- ..\..\cocoa\CCObject.cpp:92 m_uReference > 0 -- assertion failed

```

# Answer
> 2 votes
You should retain each animation created in the last line of `HelloWorld::createAnimation()`. something like `_charanimation[a]->retain()`. And later when this class is getting destroyed (in `HelloWorld::~HelloWorld()` or whenever you don't need animations any more) you should release all those classes you retained the animations to mark they are not needed any more. Note that you should not delete anything, if those animations where needed in some other class, deleting them will result in that other class malfunctioning. And if it's not needed anywhere else, releasing an instance of `CCObject` (grand parent of all cocos2dx objects) will automatically delete that instance which means that object will be deleted twice that will result in access violation.

---
Tags: c++, animation, spritesheet, cocos2d-x
---


# Question
Title: How to switch sprite animations in cocos2d-x?
I have a "GameCharacter" class where I have a sprite for my main character in the game, I loaded the frames and animations correctly. I can switch between animations with single touches or swiping gestures. Right now I can rotate between animations.

In my touch funtion of my scene I have this:

```
_mychar->RunAnimation(id);

```

where id is the ID of the animation, just an integer I change with every touch.

the method works like this:

```
void GameCharacter::RunAnimation(int a){

    _sprite->stopAllActions();
    if(a<_animation.size() && a>=0){
        _sprite->runAction( CCRepeatForever::create(_animation[a]));
    }
}

```

`_animation[]` is just a vector with `CCAnimate*` objects retained (I release them later when I destroy the GameCharacter).

I have 2 idle animations, I want to switch between them randomly, for example, I want to "queue" the first animation 3 to 5 times and the second 1 to 2 times, and repeat like this forever... also, I want to interrupt this "infinite random idle animation" with a touch that makes the character run another animation until it ends (for example a jump animation) and when it ends, just get to the idle animation. I don't know if I explained well, I hope you can understand me.

The id for the animations are:

* 0-idle1 (3 frames)
* 1-idle2 (6 frames)
* 2-jump (12 frames)
* 3-walk (12 frames)

Right now, i just need to be able to get the character in that idle state (random times between animations 0 and 1) and whenever touch, the jump animation is done once and at the end the idle start again...

I will solve the walking animation later.

Thanks in advance!

# Answer
> 2 votes
First of all, I need to notify you that my answer needs a slight modification to your approach in RunAnimation() to be able to let this answer works.

Personally I don't recommend you to use that version of RunAnimation() function as it always executes the code with CCRepeatForever manner. My answer here can be applied with your case with a slight modification to your RunAnimation(). I recommend you to cache all **animations**, and **actions** in time of loading/creating character phase then when you need to play them you play it in separate function ie. walk(), idle(). We can combine using them later.

Please note that I mean both of animation and actions. This will benefit for more complex animation handling similar to combo system for beat'em up game later on. It's cleaner. All in all this question is complex if we need to cover all cases and handle stuff properly, you will see why at **Ideas** section below.

Basically you have to utilize using CCRepeat, and CCSequence to create one combined action to be used for running animation. As always, keep CCRepeatForever away from other CCActions context. It should not be mingled around. I always treat CCRepeatForever as a special case (special care) I need to pay attention to.

**First question**

About playing 3-5 times of first idle animation, then 1-2 times of second idle animation then loop both of them endlessly, you can do this by using the similar code as follows.

```
CCAction *_cached_idleAction = CCRepeatForever::create(CCSequence::createWithTwoActions(CCRepeat::create(_cached_idle_anim_1, 5), CCRepeat::create(_cached_idle_anim_2, 3)));

```

Then you use

```
_cached_idleAction

```

variable in your idle() function.

```
void GameCharacter::idle() {
    stopAllActions();
    runAction(_cached_idleAction);
}

```

**Second question**

About running idle animation after jump and walk animation, this relates to some kind of following up approach. The difficulty comes because we shouldn't mingle CCRepeatForever with any other CCAction (to be clear it won't mix and match with CCSequence, so try to avoid combining these twos).

The solution is that you create a separate function to play idle animation like the following.

```
void GameCharacter::followUpAction(){
    // simple case
    idle();
}

```

This spans into 2 cases

1) Go to idle after non-repeat-forever action (jump)

```
CCSequence *_cached_jumpAction = CCSequence::createWithTwoActions(CCRepeat::create(_cached_jump_anim, 1), CCCallFunc::create(this, callfunc_selector(GameCharacter::followUpAction)));

```

Then you normally playing jump via jump() as follows.

```
void GameCharacter::jump() {
    stopAllActions();
    runAction(_cached_jumpAction);
}

```

After jump animation finishes playing, it will play idle animation endlessly.

2) Go to idle after repeat-forever action (walk)

Because you're walking (it's repeat-forever), you need to call

```
stopAllActions()

```

to stop it first, then call walk(). Thus it means there's no automatic-sense like in the 1st case. You need to detect it via code which time you need to make it stopped and then run another repeat-forever action subsequently.

**Ideas**

The above detail applies to normal and simple case. In order to cover all cases and handle things properly, we need to keep track of

* The current state of character in which action (or say animation) it's acting (or playing).

You may need to inject CCCallFunc in each action created for all character's actions in order to set its state whenever it plays such animation. You don't set the state when you call runAction() because the animation will play next frame and not the same time as setting state and also remember that we can chain different action (state) inside one action.
* previousAction and currentAction

stopAllActions() is not a cure. If you call this in the mid and intention to switch animation, you will probably have a high chance to stop other not related to animation ie. knockback translation due to hit-effect from enemies. Thus a character will freeze and such knockback effect won't properly apply. To solve this, we have to keep track of those two actions and stop it accordingly, **not all**.
* followUpAction() is a key

---
Tags: c++, animation, sprites, cocos2d-x
---


# Question
Title: Enumerating full game tree for small board game
I am trying to list all the possible positions in a small board game (nannon) (using C++)

So far I have decided to split it into two parts, the pieces that are in home positions and end positions (which aren't on the board) and the pieces that are in play (on the board).

Now, I can list the positions when the pieces are on the board with the STL algorithm next\_permutation (on a 6 point structure like : point\_1 = "White", point\_2="empty"......point\_5="Black", point\_6="empty")

I am left with how to list all the positions of pieces which are off the board.

I have decided to have a set of bins:

white in home position
white in end position
White in play
black in home position
black in end position
black in play

white has three pieces that can be put in any of these bins (e.g 2 in home bin and 1 in play bin), same goes for black, like this:

white in home position = 2
white in end position = 0
White in play = 1
black in home position = 0
black in end position = 1
black in play = 2

Any ideas of how I go about this?

p.s: (i tried just adding the home/end/in-play bins to the "board" structure and running next\_permutation but that gives nonsensical positions like black pieces in the home bin. I guess I could just list them ALL and then prune the nonsensical ones but that seems like over kill)

# Answer
Instead of listing the positions and enumerating which pieces can be in them, I might try listing the pieces and enumerating the positions where they can be. That way you don't have to worry about representing empty positions.

Another thing to cut down on combinations is to sort the pieces by position, to eliminate combinations that differ only by changing the order of pieces. So if you placed the first piece in position 3, let's say, you wouldn't consider positions 1-3 for the second piece; it would be limited to positions 4 and higher (assuming that only one piece can be in a position). The third piece would be limited to positions past the second piece, and so on. You have to be careful to ensure you have enough positions left to place all the pieces, so there are upper limits on each piece's position as well.
> 0 votes

---
Tags: c++, algorithm, software-engineering, tree
---


# Question
Title: Using a Vertex Buffer and DrawUserIndexedPrimitives?
Let's say I have a large but static world and only a single moving object on said world.

To increase performance I wish to use a vertex and index buffer for the static part of the world.

I set them up and they work fine however if I throw in another draw call to `DrawUserIndexedPrimitives` (to draw my one single moving object) after the call to `DrawIndexedPrimitives`, it will error out saying a valid vertex buffer must be set.

I can only assume the DrawUserIndexedPrimitive call destroyed/replaced the vertex buffer I set. In order to get around this I must call `device.SetVertexBuffer(vertexBuffer)` every frame. Something tells me that isn't correct as that kind of defeats the point of a buffer?

To shed some light, the large vertex buffer is the final merged mesh of many repeated cubes (think Minecraft) which I manually create to reduce the amount of vertices/indexes needed (for example two connected cubes become one cuboid, the connecting faces are cut out), and also the amount of matrix translations (as it would suck to do one per cube). The moving objects would be other items in the world which are dynamic and not fixed to the block grid, so things like the NPCs who move constantly.

How do I go about handling the large static world but also allowing objects to freely move about?

# Answer
Don't use DrawUserIndexedPrimitive... create an individual vertexbuffer for your moving objects.. or group all your moving objects in a vertex buffer to share it...

in your object draw call, you can set an individual indexbuffer and transform the position passing the world matrix to the effect
> 0 votes

---
Tags: xna, 3d, xna-4.0
---


title: Registering InputListener in libGDX

text:
# Question
Title: Registering InputListener in libGDX
I'm just getting started with libGDX and have run into a snag registering an InputListener for a button. I've gone through many examples and this code appears correct to me but the associated callback never triggers ("touched" is not printed to console). I'm just posting the code with the abstract game screen and the implementing screen. The application starts successfully with a label of "Exit" in the bottom left hand corner, but clicking the button/label does nothing.

I'm guessing the fix is something simple. What am I overlooking?

```
public abstract class GameScreen<T> implements Screen
{
    protected final T game;
    protected final SpriteBatch batch;
    protected final Stage stage;

    public GameScreen(T game)
    {
        this.game = game;
        this.batch = new SpriteBatch();
        this.stage = new Stage(0, 0, true);
    }

    @Override
    public final void render(float delta)
    {
        update(delta);

        // Clear the screen with the given RGB color (black)
        Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(delta);
        stage.draw();
    }

    public abstract void update(float delta);

    @Override
    public void resize(int width, int height)
    {
        stage.setViewport(width, height, true);
    }

    @Override
    public void show()
    {
        Gdx.input.setInputProcessor(stage);
    }

    // hide, pause, resume, dipose
}

public class ExampleScreen extends GameScreen<MyGame>
{
    private TextButton exitButton;

    public ExampleScreen(MyGame game)
    {
        super(game);
    }

    @Override
    public void show()
    {
        super.show();

        TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle();
        buttonStyle.font = Font.getFont("Origicide", 32);
        buttonStyle.fontColor = Color.WHITE;

        exitButton = new TextButton("Exit", buttonStyle);
        exitButton.addListener(new InputListener() {
            @Override
            public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                System.out.println("touched");
            }
        });
        stage.addActor(exitButton);
    }

    @Override
    public void update(float delta)
    {
    }
}

```

# Answer
The solution to this was answered by a kind user in the libGDX chatroom.

In order for touchUp to be triggered, touchDown must also be implemented.

```
exitButton.addListener(new InputListener()
{
    @Override
    public bool touchDown (InputEvent event, float x, float y, int pointer, int button)
    {
        System.out.println("touchdown");
        return true;
    }
    @Override
    public void touchUp (InputEvent event, float x, float y, int pointer, int button)
    {
        System.out.println("touchup");
    }
});

```
> 2 votes

---
Tags: libgdx, input
---


# Question
Title: How can I create and animate 2D skeletons for HTML5 Javascript games?
I'm trying to make a 2D fighting game in HTML5(somewhat like street fighter). So basically there are two players, one AI and one Human. The players need to have animations for the body movements. Also, there needs to be some collision detection system. I'm using createjs for coding but to design models/objects/animations, I need some other software.

So I'm looking for a software that can:

1. easily make custom animation of 2d objects. The objects structure(skeleton etc.) will be same once defined but need to be defined once.
2. Can export the animations and models in a js readable format(preferably json)

Collision detection can be done easily after the exported format is loaded in a game engine.

For point 1, I'm looking for some generic skeleton based animation. Sprite-sheet based animations will be difficult for collision detection.

# Answer
> 1 votes
You're probably looking for something like Spine. Spine is a great tool that recently received a round of funding with a bunch of generic run times that does exactly what you want. (Yes, there is a Javascript one.) Everything you need is available in Spine, just keep in mind:

* It's not free - it's 75$ but well worth the price if you'll be doing a lot of these.
* The software isn't fully mature at the time of writing - but it's definitely progressing very quick.

# Answer
> 0 votes
I personally suggest you use a free 3d Software and work with dummy boxes for the different parts.

There are two software (packages) i can think of

* blender (free, also for comercial stuff)

can export to various formats, i dunno about animation stuff but it should be possible to read it out and export it with a python script
* houdini (free for no ncomercial usage)

is extremly powerful, you can use python scripts for animation data readout (or read the position and write it into a file)

can also export to various formats

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


title: OpenGL doesn't draw (3.3+)

text:
# Question
Title: OpenGL doesn't draw (3.3+)
**Brief:** I've been following this tutorial about OpenGL for 2 days, and I still can't have a triangle drawn, so I'm asking for help here. The tutorial is turned to *OpenGL version 3.3* programing, using vertex arrays, buffers, etc. The libraries are: *GLFW3* and *GLEW*, and I setted them by myself. The screen keeps black all the time.

**Full code:**

link here (It's just like a Hello World opengl program)

**Further Details:**

* I get no errors at all.
* I downloaded a software to test my video card, and it supports *OpenGL 4.1+*
* Standard OpenGL code for drawing (from earlier version) such as this one works normally.
* I'm using Microsoft Visual Studio 10.0
* I presume all the OpenGL implementation was dune right: I added *Additional Dependences* to the linker as *glew32.lib*, *opengl32.lib*, *glfw3.lib*. The glew.dll was placed at SysWOW64 - because I'm running window 64bits, and glew is 32.

**Notes:** I've been working hard to find out what this is, but I can't find. I would appreciate if anyone could test this code for me, so I can know if I implemented something wrong, and that its not my code.

# Answer
> 3 votes
As I discovered the solution based on Polar's argument, I will just answer my own question.

As he said:

> I'm pretty certain that shaders are mandatory for newer versions of OpenGL, even if it's merely a flat shader.

Just drawing points from a buffer, calling the method

```
glDrawArrays(GL_TRIANGLES, 0,3);

```

for instance, won't necessarily draw something (on new versions of OpenGL). It requires shaders. To make sure that something was being rendered, and that the black screen wasn't an uncompatibility problem, I called the method

```
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

```

before entering the main loop. Instead of a black window, here is the result. Problem solved.

---
Tags: opengl
---


# Question
Title: How to control in the vertex shader where pixel ends up in the renderTarget?
What if I have an arbitrary renderTarget, that is smaller than the screen (say it is 1x1 pixel) and I want to make sure in the `VertexShaderFunction` that all my pixels end up exactly in that 1 pixel region? No matter what I do, they all seem to get culled at some point, though `GraphicDevise.Clear()` works OK.

Where is the top left corner of the renderTarget Vertex-shader-vise? I tried `output.Position` = (0,0,0,0)/(0,0,0,1)/(1,1,1,1)/(-0.5,0.5,0,1) NOTHING works!

Fullscreen quad is not an option 'cause I actually need to process geometry in the shaders to get the results I need.

# Answer
> 0 votes
If anyone is reading this, there is a way to control pixel position in the vertex shader, ofcourse :). But you need to remember two things:

1) if all vertices end up in the same position - no pixels will be drawn, so you must specify a region between at least 3 dots;

2) the GPU will interpolate the region you entered across your rendertarget, minding the latter's size, so in the end for every triangle you draw, only one pixel will get drawn for pixel slot in the rendertarget. So two pixels will end up in the same spot fighting for it ONLY IF they belong to two different triangles.

One more thing I wanted to add. I was asking this question as I had an idea about a pixel-perfect collision detection system in 2d world FOR A NON-PIERCING BULLET (the piercing one can be easily implemented with occlusion query and stencil buffer). I dropped the idea as it's solution was infeasible and inefficient. However, there is one approach one could theoretically employ. You don't even need DX10/11 for this. The thing is, if you have your scene with monsters drawn into it using their numbers and not colors, and it you then use this scene as a texture in a shader, you can paint a bullet over it and compute where it hits the monsters. Each pixel will even know WHICH monster it hit, and you can even compute the difference from the end of the barrel to the pixel. However, you will end up with a tone of pixels and won't be able to tell which one is the first one in the bullet's way. To solve that, you can take call tex2D() in each pixel's shader multiple time IF you can compute the UV offsets for EVERY pixel of the bullet's trajectory. Then each pixel will know it's hit data, and the data for neighboring pixels and output only the data for the nearest hit. Thus you will end up with a line that consists of several blocks of pixels. In that case you will need to run the shader one more time to refine it to a line consisting of pixels each of which has the same data - which monster is the first one to hit. Then you simply call Texture.GetData for a single pixel region and end up with a monster number. If you will make a call in a different thread - you can read data later without program stalls.

---
Tags: c#, xna-4.0, shaders, hlsl, vertex
---


# Question
Title: C# Item system design approach, should I use abstract classes, interfaces or virutals?
I'm working on a Resident Evil 1/2/3/0/Remake type of game. Currently I've done a big part of the inventory system (here's a link if you wanna see my inventory, pretty outdated, added a lot of features and made a lot of enhancements)

Now I'm thinking about how to approach the items system, If you've played any Resident Evil game or any of its likes you should be familiar with what I'm trying to achieve. Here's a very simple category I made for the items:

So you have different items, with different operations you could perform on them, there are usable items that you could use, like for example herbs and first aid kits that 'using' them would affect your health, keys to unlock doors, and equipable items that you could 'equip' like weapons. Also, you can 'combine' two items together to get new one, like for example mixing a green and red herb would give you a new type of herb, or combining a lighter with a paper, would give you a burnt paper, or ammo with a gun, would reload the gun or something. etc. You know the usual RE drill.

Not all items are 'transformable', in that, for example: lighter + paper = burnt paper (it's the paper that 'transforms' to burnt paper and not the lighter, the lighter is not transformable it will remain as it is) green herb + red herb = newHerb1 (both herbs will vanish and transform to this new type of herb) ammo + gun = reload gun (ammo state will remain as it is, it won't change but it will just decrease, nothing will happen to the gun it just gets reloaded)

Also a key note to remember is that you can't just combine items randomly, each item has a 'mating' item(s).

So to sum up, different items, and different operations on them. The question is, how to approach this, design-wise?

I've been learning about interfaces, but it just doesn't quite get into my head, I mean, why not just use classes with the good old inheritance? I know the technical details of interfaces and that the cool thing about them is that they don't require an inheritance chain, but I just can't see how to use them properly, that is, if they were the right thing to use here.

So should I go with just classes and inheritance? just like in the tree I showed you? or should I think more about how to use interfaces? (IUsable, IEquipable, ITransformable) - why not just use classes UsableItem, Equipable item, TransformableItem?

I want something that won't give me headaches in the long run, something resilient/flexible to future changes. I'm OK using classes, but I smell something better here.

The way I'm thinking is to possibly use both inheritance and interfaces, so that you have a branch like this: item -\> equipable -\> weapon. but then again, the weapon has methods like 'reload' 'examine' 'equip' some of them 'combine' so I'm thinking to make weapon implement ICombinable?... not all items get used the same way, using herbs will increase your health, using a key will open a door, so IUsable maybe?

Should I use a big database (XML for example) for all the items, items names, mates, nRowsReq, nColsReq, etc?

Thanks so much for your answers in advanced, note that demo 3 is coming after I'm done with items :D

# Answer
This is probably not the answer you were hoping for, but I think the best way to implement this is to use both inheritance AND interfaces.

The inheritance tree you describe above seems pretty good, in that it's fairly complete (you may find you want to add some extra abstract classes for common functionality between some of those branches, but that's an easy change to make. The obvious example to me is "Firearm" between weapon and both Rifle and Handgun).

However, you mention (correctly) TransformableItem in your question, and that's not in the list of classes. Where would you add it if you wanted to make it a class? You could make it a child of Item, and have everything else inherit from it, but then EVERY class would be transformable, and that's no what you want. Anywhere else in the inheritance structure though, and not every desired class inherits it.

So a way (certainly not the only, and not necessarily the best, but that recommendation would require a lot more knowledge of your game) to implement this is to have herb, firearm, and some of your other item classes implement ITransformable. Then functionality is common between classes, re-used, and not present where you don't need it. Testing for .Implements(ITransformable) allows you to decide when to show those menu items, and the methods for combining take ITransformable parameters to stop you from trying to transform a first aid kit (or whatever).

In short, not every class should be an interface, but some functionality should be wrapped in one, so it can be applied to "arbitrary" classes within an inheritance tree.
> 5 votes

# Answer
Have you tried an component based entity system? Here's an example I think would be good to check out: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
> 1 votes

---
Tags: c#, unity, design-patterns, databases, inventory
---


title: .md5mesh normals are not smooth

text:
# Question
Title: .md5mesh normals are not smooth
I'm currently working on a project that requires me to load .md5mesh format and draw it.

Following this link I've managed to load the mesh into the engine successfully, but a problem arises when calculating normals; they just don't seem to smooth.

To clarify that it was not my rendering or shader code that was the problem, I loaded a model of .OBJ format, and that lights smoothly.

The mesh is calculated correctly too, as I am able to load in complex models with multiple joints and mesh parts.

Here's a screenshot of the lighting.

And here is how I currently calculate the normals (All normals are set to zero before computing):

**EDIT** Amended the psuedo-code to be more accurate to what I have. The original may have been confusing.

```
for (unsigned int i = 0; i < NumberOfTriangles; i++)
{
    Math3::vec3 r, s, result;
    Math3::vec3 p1, p2, p3;

    p1 = Triangle[i].Vertex[0];
    p2 = Triangle[i].Vertex[1];
    p3 = Triangle[i].Vertex[2];

    r = p2 - p1;
    s = p3 - p1;

    result = Math3::Cross(s, r);

    // Add the triangles face normal to each vertex
    // The Vertex's are not local to the triangles.
    // Triangle[i].Vertex[j] is just an index.
    Vertex[Triangle[i].Vertex[0]].normal += result;
    Vertex[Triangle[i].Vertex[1]].normal += result;
    Vertex[Triangle[i].Vertex[2]].normal += result;
}

```

After the loop I normalise each vertex normal to find the average normal.

**EDIT** Here is how I find the average normal:

```
for (unsigned int i = 0; i < NumberOfVerts; i++)
{
    float nx = Vertex[i].normal.x;
    float ny = Vertex[i].normal.y;
    float nz = Vertex[i].normal.z;

    float len = sqrt(nx * nx + ny * ny + nz * nz);

    Vertex[i].normal.x /= len;
    Vertex[i].normal.y /= len;
    Vertex[i].normal.z /= len;
}

```

As you can see in the image the .md5mesh model is shading flat instead of shading smoothly like the .OBJ model.

So what am I missing?

# Answer
It turns out that it was an error in my rendering code.

The code in my question does work out the normals correctly, so if anyone is stuck, my code should work.

The problem was related to how I was interpreting the index buffer.
> 0 votes

# Answer
The way you calculate your normals, you end up with this because you take the cross product of the triangle sides.

Where red circles are normals pointing directly at the screen. Sideways it looks like this (both black lines are triangle faces seen from the side)

Notice how for every face, the vertices that make it up are parallel to each other. Because of this, the interpolated value of the normals along the entire face is the same as the value at every vertex!

Instead, your normals should look like this

In which case the interpolated value will vary along the face and give you non-flat shading. I guess the easy way to calculate such normals would be to make another pass and set every vertex's normal to the normalized sum of the normal assigned to it for every face that shares it.

Your problem is that you're not calculating the average normals properly. Basically you seem to only be normalizing the ones you calculated.

Since your faces are all triangles, the pseudocode would look something like this (suboptimal naive algorithm warning)

```
foreach vertex in mesh.vertices
  //Find the 3 vertices belonging to different faces that are actually the same vertex but with different normals
  vertex shared_vertices[3] = mesh.find_vertices_at_same_position(vertex)
  normal = sum(shared_vertices)
  normal = normalize(normal)

  foreach v in shared_vertices
    v.normal = normal

```

The calculated normal will then be the blue arrow in this image:

Another cool thing is that once that work is done you could actually share the vertices between faces instead of having 3 copies since all their attributes are the same (thereby saving 2/3 of the memory required to hold your current vertex data)
> 2 votes

---
Tags: opengl, lighting, 3d-meshes, normals
---


# Question
Title: How do I make something I flash/blink more frequently as it gets closer to disappearing?
In my game when you kill an enemy they may drop something like a health pack or gold. I want this to have a time limit so that it eventually disappears if you don't pick it up. I want the item to flash more frequently the closer the drop gets to "death". How do you do the "more frequently flashing" algorithm?

# Answer
My concern with either of the approaches currently offered is that they'll both lead to 'variable-speed' blinking, which could not only be distracting for the players but also make it hard to gauge exactly how long an object has left before it vanishes. Instead, somewhere in your parameters (whether they be global for the renderer or on a per-object basis) I would have four constants: `slowBlinkTime`, `slowBlinkRate`, `fastBlinkTime` and `fastBlinkRate`. When rendering, if your object's remaining life is less than `fastBlinkTime`, then blink it at `fastBlinkRate`; otherwise if it's less than `slowBlinkTime`, then blink it at `slowBlinkRate`. If you wanted to go a step further then you could have an array of distinct `blinkTime`s and `blinkRate`s and check them one by one, but in practice that's likely to be overkill and just having 'warning' and 'critical' states should be enough. The code would look something like this:

```
float blinkCycle;
if ( entity.timeLeft < fastBlinkTime ) {
  blinkCycle = entity.timeLeft/fastBlinkRate;
} else if ( entity.timeLeft < slowBlinkTime ) {
  blinkCycle = entity.timeLeft/slowBlinkRate;
}
blinkCycle = blinkCycle - floor(blinkCycle); // find blinkCycle 'mod 1'
if ( (entity.timeLeft < slowBlinkTime) && (blinkCycle < 0.5f) ) {
  renderBlinked(entity); // this should be the 'blinked' state, whether flashed or missing
} else {
  renderNormal(entity); // the normal render for the entity
}

```

Note that this code presumes a half-on, half-off blink cycle (that's what the `0.5f` in the test represents), but could easily be tweaked for something like two-thirds on, one-third off just by tweaking the appropriate constant. This also doesn't do anything to 'synchronize' blinking between the fast and slow states, but that's relatively straightforward to polish.

This should be straightforward to plug in, and it will have the IMHO substantial advantage that players will be able to see the switch from 'slow' to 'fast' blinking and know exactly how long they have left. I would start with parameter values like 5s for `slowBlinkTime` and 0.5s for `slowBlinkRate`, and 2s / 0.25s for `fastBlinkTime` and `fastBlinkRate`, but that's definitely dependent on your particular game.
> 2 votes

# Answer
If t goes down from T to 0, you could use something like sin((T - t)²) then if the number is \> 0 you draw the object, if it's \< 0 you don't

---

I've tried this out myself and I had to tinker with it. For me T was 100. This equation made things blink super fast the whole time. So to slow it down, I changed the equation to sin(((T - t)/10)²). This was after tinkering around with the numbers like /6 and /7.

I also tried this: sin((T - t)² * 1/100)

And then I didn't like how the drop seemed to be invisible almost as much as it was visible. I wanted it to rarely be invisible. I accomplished that by doing this: sin((T - t)² * 1/100) + .5 That + .5 shifts the sine "line" up so that it doesn't become \< 0 as often.

None of this worked exactly the way I wanted. The problem is that the blinking would start too soon. I wanted the drop to be visible for 3 seconds and then start blinking. To accomplish that, I did something like this:

```
isVisible(drop)
  if drop.t > x
    return true
  else
    sin((T - x - drop.t)² * 1/100) + .5 >= 0

```

That `x` would be the 3 seconds.

Also worth noting is that this is the tool I used the whole time to visualize how the blinking would look. I think this would have taken 5x longer without the visual tool.
> 14 votes

# Answer
Maybe with the help of another variable?

```
current_length = 4
length_decrease = 0.5
current_time = current_length

function update(delta_time)
    if current_time > 0 then
        draw()
    end
    current_time -= delta_time
    if current_time < -current_length then
        current_length -= length_decrease -- feel free to get creative here
        if current_length < 0 then
            disable_object()
        end
        current_time += current_length * 2
    end
end

```

It is a bit longer than the solution you proposed yourself, but you save yourself costly `sin` and `pow` operations, and you have much more control over how the blinking goes faster.
> 4 votes

---
Tags: algorithm, rendering
---


# Question
Title: Adding gesture recognizer (or dragging) to CCSprite
I'm trying to allow a CCSprite to be dragged across the screen. I've succeeded so far by doing it on a Layer level (from this tutorial). However, this only allows ONE sprite to be dragged at a time as the method implementation can only identify a single sprite to move at a time.

I'd like to be able to perhaps add a gesture recognizer or somehow implement ccTouchesBegan/Moved in my own little CCSprite subclass.

However, from what I understand, you can't just add gesture recognizers to CCSprites. ccTouchMoved are also not available on CCSprites?? Really confused as to how to implement touches on Cocos2D.

What is the easiest way to add some position translation code to a CCSprite so it can be dragged around? Thanks!

# Answer
> 1 votes
My logic here is that a Scene or Layer can need to act differently for the touch events depending upon what was touched.

So on the `touch begin` if you did indeed touch the sprite in question, I set a boolean.

On the `touch end` if that boolean is true, you take the point at where you dropped the sprite, check to see if the sprite is indeed contained in the spot you stopped the touch event and then set that as the new position for the sprite.

Something like:

```
bool GameScene::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    CCPoint touchLocation = touch->getLocationInView();
    touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );

    CCRect meatboyBounds = meatboy->boundingBox();

    if(meatboyBounds.containsPoint(touchLocation))
    {
        m_bSpriteBPressed = true;
    }

    return true;
}

void GameScene::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
    if (m_bSpriteBPressed)
    {
        CCPoint touchLocation = touch->getLocationInView();
        touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
        m_bSpriteBPressed = false;
        meatboy->setPosition(touchLocation);
    }

}

```

# Answer
> 0 votes
Hmm...not sure if this will help you.

I've actually created my own abstraction of the CCTouchDispatcher and subclassed CCSprite. Through that dispatcher, I register all my sprites/layers/etc. Since the dispatcher can do all the cocos2d touch events, I can send message to those sprites.

I'm fond of subclassing cocos2d classes so that it'll fit to my needs and make the development faster.

---
Tags: sprites, ios, cocos2d-iphone
---


title: Generating terrain on GPU

text:
# Question
Title: Generating terrain on GPU
In my engine I create infinite terrain with usage of Perlin noise alghoritm computed on CPU.

Creation of terrain goes like this:

* If camera is near unloaded patch, create it
* Compute 513x513 noise array with given boundaries
* Compute normals, tangent, binormal, indices
* Pass data to vbo

---

Pros:

* Only needs to be rendered when needed
* Easy to make collision

---

Con

* Slow 64 513x513 patches are created in 3,1s(one thread). For each tile ~20ms noise creation, ~25ms vertices, normals, tangent, bitangent, indices. When camera moves fast, user can notice tiles loading.
* memory consuming???

Now I was wondering how to speed this up by generating terrain completely on GPU But there are some doubts:

* If shaders run every frame, isn't this computation power waste to compute noise over and over? This can be avoided by writing result into RBGA texture and used later in vertex shader for displacement, but increase memory usage. From the other hand if the creation would be super fast, only visible tiles should stay in memory. However detaching buffer causes gpu-cpu sync which may slow down the app (am I right?)
* If the terrain is just a flat grid displaced by vertex shader, the same work needs to be done on CPU to compute height and normal at given point for collision.
* This is just a concept, but to speed everything up I was thinking about projecting grid on viewport so only minimal amount of vertices is used. Do you think this would work?

My final question is:

What the best/fastest/broadly used technique to create infinite terrain on GPU?

# Answer
Well if I was to try to use the GPU for such a thing, I think I would go for compute/opencl/cuda.

However regardless of using the GPU or CPU (which is what I actually do), I would do it in an asynchronous manner, deciding you need some new terrain for the current frame is likely too late (e.g. consider 1000ms / 60 = 16.666ms, and the entire frame wants to fit into that).

Start generating (or loading from compressed files) terrain on a worker thread, and make it available to the rest of the game and rendering once that worker has finished, generally this will be the next frame, or perhaps the frame after that, so the user won't really notice the difference there, but it makes things smoother.
> 2 votes

---
Tags: terrain
---


title: C# XNA4 2D Collision Detection

text:
# Question
Title: C# XNA4 2D Collision Detection
I am working on a 2D engine in Xna and am running in a bit of trouble with Collision implementation. What I want to do is have an interface ICollidable that I can add to GameObjects that are collidable.
I am trying to get it to work by using this awnser: https://gamedev.stackexchange.com/a/40432/33751

My question is how do I add the objects that use ICollidable to the List in the CollisionManager dynamically?

By case would be that the manager 'sees' what objects use the ICollidable interface and automatically add it to the list.

Second question is, how can I get the properties and stuff from the objects that contain the interface to actually preform the collision detection in CollisionManager? would a simple cast suffice?

ICollidable:

```
interface ICollidable
{
    void onCollision(ICollidable other);
}

```

CollisionManager:

```
class CollisionManager : GameObject
{

    private List<ICollidable> collidables = new List<ICollidable>();

    public CollisionManager(Game game)
        : base(game)
    {
        game.Components.Add(this);
    }

    void addCollidable(ICollidable obj){
        // This function needs to be called when ICollidable is inherited dynamically
        collidables.Add(obj);
    }

    public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
    {
        base.Update(gameTime);

        for (int i = 0; i < collidables.Count; i++)
        {
            for (int a = i + 1; a < collidables.Count; i++)
            {
                if(collision(collidables[i], collidables[a])){
                    collidables[i].onCollision(collidables[a]);
                }
            }
        }

    }

    private bool collision(ICollidable obj)
    {
        // How can i get obj's properties etc for checking collision.

        return false;
    }
}

```

PS. Never worked with interfaces in c# before, if I am doing it completely wrong, please let me know

Thanks in advance.
Yme-Jan

# Answer
For example if you want to get the ICollidable's "BoundingBox" (Rectangle), you have to add it to your interface.

```
interface ICollidable
{
    void onCollision(ICollidable other);
    Rectangle boundingBox {get; set;}
}

```

Of course you have to implement them in the Class which implements the interface too.
> 0 votes

---
Tags: 2d, collision-detection, xna-4.0, sprites, interface
---


# Question
Title: How do I represent walls in a 2D tile based map?
I'm trying to create a simple 3D(2D) Dungeon Crawler but I am going to be using simple flat images to show the user they are in a "3D" world. Now what I mean is something like Sword and Serpents on the Nintendo.

Now as you can see on the right is a map, and on the left is the dungeon screen, I don't need help with the left screen no no. But on the right is the map, now I'm trying to think of a way I could represent this. I was thinking of using a 2D array, and doing something like this

```
w,w,w
h,o,o
w,w,w

```

So the H is the hero, and in front of him is two open spaces. so the hero can see two blocks around that is it. But if you look at the game, the player can move like this

```
h,o,o
o,o,o

```

so everywhere is open. but there is a wall between some blocks. Do you think an ID system would be better for example

1 = open space with walls on the north and south

2 = open space with walls only on the north

3 = open space with walls only on the south

etc, etc.

Do you think the ID system is way better or the use of W for a wall.

# Answer
> 2 votes
You can make your grid store the areas *between* walkable areas. You don't need to store your hero into the map itself, so that doesn't require you to have positions for walkable areas where the hero is standing. You might need them for other purposes, though.

You could also store both the walkable areas, keyed by floor/ceiling type (e.g. stone floor, water, etc.) and also the walls separately.

You can store both by alternating between wall data and floor. So two adjacent tiles with a wall between would be stored as `[floor,wall,floor]`. If you accessed tiles before at a particular `X,Y` location you would now be accessing them at `X*2+1,Y*2+1`. The left/west wall would be at location `X*2,Y*2+1` and the top/north wall would be at `X*2+1,Y*2`.

I hope that makes sense. A picture would probably help, sorry.

# Answer
> 0 votes
Better depends on what you want.

Example, is a wall a wall?

By that I mean is a wall impassable from both sides (in which case the W case is easier)?

Or for example do you want to have walls which block from one side and lets you pass through from the other. In this case your ID system lets you do that (on one side you mark a wall on the other you don't).

BTW don't do IDs but use flags (basically the same but different handling. Your example says 1 has a wall north and 2 has a wall north, so you always have to check for every possible ID which includes a wall north, given the other 3 options of either wall or not that would be 8 numbers. If on the other hand you use bit 0 as a flag for wall north you can simplify this to (ID & 0x01 -\> Wall to the north).

Take also into account that using the first system (i.e. Wall as a separate cell) simplifies things. If you set a cell to wall it is a wall. In the ID case if you put a wall at the northern side you also have to put a wall at the southern side of the northern cell to truly generate a wall.

So just think about what properties the ID system enables (and which you will actually use) and whether this justifies the overhead you have to pay to use a more complicated system.

# Answer
> 0 votes
Do a pixelated map. use getImageData for each pixel of the map in series. make an if statements to check color on ur pixelated map and draw right tiles according to the color

---
Tags: 2d, game-design, javascript, html5
---


title: tunnel effect cocos2d

text:
# Question
Title: tunnel effect cocos2d
I am looking to create a similar tunnel effect in COCOS2D (iOS). Could anyone suggest any pointers?

ref Video 1

ref Video 2

Till now I have tried with several ring shape sprites with decreasing scale and positioned center to a same point and keeping Z decreasing as well for each smaller sprite.

With that, animating it with CCScaleTo and changing the size to 2.0 with animation duration but it does not come anyway near to the tunnel effect shown in the reference.

Thanks, sam

# Answer
> 10 votes
I found the implementation description from the author of this effect:

> It surely was a lot of work to create the depth illusion in a 2D plane.
>
> The principle is very easy though: circles start in the middle of the screen with scale 0. Then the first circle of the tunnel starts scaling proportionally to the time elapsed (linear scaling doesn't work) and after some time the second circle starts scaling, then the 3rd, and 4th and so on.
>
> You then lower proportionally the alpha value for the circles (the ones in the far back have alpha value lower than the ones in front to give the illusion of blur), you define a path that every circle has to follow, moving the X and Y coordinates of it, then you put a spaceship in the middle of the screen. Tilting the device makes the tunnel to shift left and right, up and down (but that gives the impression that the spaceship is moving instead!).
>
> Once the circles go out of the screen, they are quickly faded and put back into initial position (to save memory so I don't need to create new circles but I reuse the same ones).
>
> Sorry about my english, but I hope that explained the general idea :)

# Answer
> 1 votes
I would probably try to get it sorted with a background layer and particle effets. You could test the effects in particle designer and play them in the backgroung layer afterwards.

# Answer
> 1 votes
You're almost there with having multiple ring sprites of decreasing Z value and scale. Just don't center them all.

You need to keep track of the point where you want the tunnel to hit the far away event horizon. You can move that point around over time however you like.

Then, as you place each new sprite, place it at that point, scale it small, set it's opacity how you like, then start a `CCSpawn` with `CCScaleTo` and `CCFadeTo`, for example:

```
sprite->runAction(CCSpawn::create(
    CCScaleTo::create(2.0f, 1.5f),
    CCFadeTo::create(5.0f, 255),
    nullptr));

```

Pre-create all the sprites and rotate which one is in the back to keep it efficient.

# Answer
> 0 votes
To be honest I don't think that image is rendered using a 2D camera. It looks like the game is rendered using a 3D rendering system. But since you want to use cocos2d, you need to simulate that 3D transormation matrix yourself. Here is an idea to begin with: you know in a 3D scene, every object is defined by 3 scalar values, x,y, and z. The simplest method you can use is scaling as you suggested, but not as you implemented! `ccScaleTo` will result in a linear scaling over time, which will not produce 3D feel. You can start with scaling object by value of `1/z`. This is somehow identical to the simplest projection matrix you can think of! if you feel even that doesn't satisfy you, take a look at more modern and more complex projection matrices.

Side note: implementing custom projection matrix in cocos2D will be a little bit dirty. if you really don't like the effect, I strongly suggest changing your engine to one with 3D support.

# Answer
> 0 votes
Here is how I did it, in pseudo-code

Activate Tunnel-effect:

1. Create a CCRepeatForever(CCFunc(createCircle))
2. Add a node to your scene called "ViewNode"

createCircle()

1. Create layer, postion in center of Scene. Add it as child to "ViewNode".
2. run action: CCSequence( CCEaseExponentialIn(CCScaleTo) , CCRemoveSelf )
3. Put stuff in your layer, i.e. cirkels, enemies, spaceships, whatever.

Control (with parallax)

1. For all layers with tunnel-effect (i.e. children of ViewNode)
2. update anchor position based on touch position.

The position is the Vanishing Point, therefore, you can't move layers without moving the vanishing point. However, if you move the anchor point, the layer appear to move, but the Vanishing Point stays the same -- this creates a parallax effect, because moving ccp(0.2,0.2) on a close layer (large scale) has more effect than moving the same on a far-away layer.

You wrap everything in layers of the same size, to make sure that repositioning the anchor creates the same movement in all layers.

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


title: Smooth Camera Zoom Factor Change

text:
# Question
Title: Smooth Camera Zoom Factor Change
I have game play scene in which user can zoom in and out. For which I used smooth camera in the following manner.

```
           public static final int CAMERA_WIDTH = 1024;
           public static final int CAMERA_HEIGHT = 600;
           public static final float MAXIMUM_VELOCITY_X = 400f;
           public static final float MAXIMUM_VELOCITY_Y = 400f;
           public static final float ZOOM_FACTOR_CHANGE = 1f;

            mSmoothCamera = new SmoothCamera(0, 0, Constants.CAMERA_WIDTH,
                            Constants.CAMERA_HEIGHT, Constants.MAXIMUM_VELOCITY_X,
                            Constants.MAXIMUM_VELOCITY_Y, Constants.ZOOM_FACTOR_CHANGE);
            mSmoothCamera.setBounds(0f, 0f, Constants.CAMERA_WIDTH,
                            Constants.CAMERA_HEIGHT);

```

But above thing create problem for me. When user perform zoom in and leave game play scene then other scene behaviour not look good. I already set zoom factor to 1 for this purpose. But now it show camera translation in other scene. Because scene switching time it so much small that player can easily saw translation of camera that I don't want to show. After camera reposition, everything works perfect but how to set camera its proper position.

For example my loading text move from bottom to top or vice versa based on camera movement.

Any more detail you want then I can able to give you.

# Answer
> 1 votes
I can able to solve my problem with sudden camera jump using on update method. Following are the code snippet that I use to solve the problem.

```
mSmoothCamera.setZoomFactor(1f);
mSmoothCamera.onUpdate(10f);

```

---
Tags: andengine
---


# Question
Title: What is the correct way to update a physics frame rate?
I've searched around the Internet, and eventually read a suggested article, *"Fix your Timestep!"*. In accordance with the article, I came up with an update method, but I still have problems. Whenever I instantiate more objects, in my scene, I get much slower physical interaction. I've fixed other sub-systems, that they were wasting cycles during the update process, and I've tracked my physics performance drop to this point. I think the way I'm updating my physics is somehow wrong, because I'm using a fixed timing of `1.0 / 60.0` for my Box2D engine.

What are the mistakes I'm making in my update process? What is the correct way to update a physics frame rate? Here is my code:

```
void Core::Update()
{
    // Input
    this->cInput->Update();

    // Physics
    this->cPhysics->Update();

    // Keep frame rate
    static const double desiredTime = 1.0 / 60.0;
    static double currentTime = (double)(GetTickCount());
    static double accumulator = 0.0;

    double newTime = (double)(GetTickCount());
    double frameTime = newTime - currentTime;

    if(frameTime > 0.25){ frameTime = 0.25; }
    currentTime = newTime;

    accumulator += frameTime;

    while(accumulator >= desiredTime)
    {
        // Input
        this->cInput->Update();

        // Physics
        this->cPhysics->Update(desiredTime);

        // Scripts
        this->cScripts->Update();

        accumulator -= desiredTime;
    }

```

I've read that you shouldn't tie your physics frame rate to the render frame rate, so I use `this->cPhysics->Update();`. I've used my previous approach, but with a slight change; I'm not sure if what I'm doing is right, but it solved my performance issue. First, I changed `currentTime` to get time in milliseconds, instead of seconds. At the end, I've moved all of my update code to a time step loop, except for the renderers update. I still do not know if this is the correct way to go.

# Answer
> 1 votes
The problem lies here

```
    static double currentTime = (double)time(NULL);
    static double accumulator = 0.0;

    double newTime = (double)time(NULL);

```

your currentTime and newTime are roughtly the same that way, this can't work.

you need to measure the time you needed for one frame (the last frame) and sleep the remaining time till you hit your 1.0s/60s mark. Don't forget that the sleeping doesn't sleep exactly the amount of time you passed in so you need to compesate for that.

An optional way to get the used time for the frames is to use a sliding window approach for all frame times and sum the times and divide by the count.

Another important oint is to limit your delta-time you actually measured (say to 0.2 seconds) for avoiding instabilities.

**Edit 1** Example code to illustrate it

```
private double Time = 0.0;

private double deltaTArray[10];
private unsigned int deltaTArrayI;

// NOTE< this->currentTime must be set once before this is called >

void Core::Update()
{
    // Input
    this->cInput->Update();

    double newTime = (double)time(NULL);

    double deltaT = newTime - this->currentTime;

    this->currentTime = newTime;

    deltaT = min(deltaT, 0.25); // because of stability

    this->deltaTArray[this->deltaTArrayI] = deltaT;

    (this->deltaTArrayI)++;
    this->deltaTArrayI = this->deltaTArrayI % 10;

    // calculate delta T as average of the sliding window
    double deltaTAverage = 0.0;

    for( unsigned int i = 0; i < 10; ++i )
    {
        deltaTAverage += this->deltaTArray[i];
    }

    deltaTAverage = deltaTAverage / (double)10;

    // Physics
    this->cPhysics->Update(deltaTAverage);

    // Keep frame rate
    sleep(max((1.0/60.0)-deltaTAverage, 0));

    // Render
    this->cRender->Update();
}

```

---
Tags: c++, box2d, timestep
---


# Question
Title: Cocos2d When The Loading Screen Scene is loading music
When the loading screen loads objects like music cutscenes, the idea is to preload the objects, so... what should happen next? Do I transfer the objects to the next scene? or these special objects, media objects or even just images of the sprites, do they have to be part of a Singleton? According to my logic, singleton is a simple solution, that can I use whatever was preloaded in the loading screen to take to the game. The only drawback is that I have to keep management of these objects to unload them when out of the game scene.(its just an example, but its really close to what my game is doing).

The thing is, i believe there is a more elegant solution to this problem. Anyone has any suggestions? or tell me if my method is wrong?

# Answer
in Cocos2D, doesn't the music continue to play until you pause or stop it?

If I want to change music between CCScene I usually do something like:

```
_dir->Instance()->getAudioEngine()->stopBackgroundMusic();
_dir->Instance()->getAudioEngine()->stopAllEffects();

// click!
_dir->Instance()->getAudioEngine()->playEffect("click.mp3", false);

...do whatever

```

Edit:

I dont use the shared director. I created my own director object with everything I need as member variables.

I load my music like this:

```
void AppDirector::createAudioEngine()
{
    CocosDenshion::SimpleAudioEngine* ae = new CocosDenshion::SimpleAudioEngine();

    ae->preloadBackgroundMusic("Tallahassee.mp3");
    ae->preloadBackgroundMusic("bigcountry.mp3");

    ae->preloadEffect("click.mp3");
    ae->preloadEffect("tap.mp3");

    ae->setBackgroundMusicVolume(0.5f);
    ae->setEffectsVolume(0.3f);

    setAudioEngine(ae);
}

```

Edit 2:

I do this:

```
AppDirector* AppDirector::Instance()
{
    if (pinstance == 0) // is it the first call?
    {
        pinstance = new AppDirector; // create sole instance
        pinstance->initInstance(); // setup everything we need.
    }

     return pinstance; // address of sole instance
}

void AppDirector::initInstance()
{
    createFileUtils();

    createDirector();

    // set some defaults
    setIsHUDDisplayed(false);

    createTouchDispatcher();

    createAudioEngine(); // created and preloads music and sound effects.

    createOpeningScene();
}

```
> 0 votes

---
Tags: cocos2d-iphone
---


# Question
Title: Most efficient way to draw large number of the same objects, but with different transforms
I'd like to draw a large number (multiple thousands) of simple meshes (each maybe... a maximum of 50 triangles, but even that is a very large upper bound), all of which are exactly the same.

As a simple brute force way, right now I'm just doing thousands of draw calls, where I just change the transformation matrices that the shaders need and then draw the same objects again.

Of course this is hideously slow, since (I'm guessing) there are too many draw calls for the driver and my PC to handle efficiently.

What can I do to make it faster?

# Answer
The solution to this is instancing. This tutorial explains a few methods of instancing. If you have `ARB_draw_instanced` and `ARB_instanced_arrays`, use them.

The general idea is to store all of your meshes' transforms in a separate buffer object and bind that to an attribute array that uses one "vertex" per instance via `glVertexAttribDivisor`.

If, after that, you're still not running as fast as you want to, you're probably vertex processor bound. Do frustum culling on the meshes, and preferably build a BVH to traverse instead of doing the cull on all the meshes independently.
> 11 votes

---
Tags: opengl
---


# Question
Title: how to improve sprite animations to reduce FPS
My game has different, and detailed animations throughout the game. For example, the main character has an idle stance, so its not just painted still, giving him some life. Death animation, hurt animation, etc... even the background scenario has animations(which I don't think I went with the best approach here, but, it's working for now, this will be in another thread if not answered here) Anyways, the thing is, while the main character had these animations only that character was in the game at that time, so everything ran smoothly. After adding another character, the enemy, the burden of animations seems to overcharge the FPS and just slows the game down. The most obvious of this problems was that the spritesheet I was using was 1 per character, I figured how to use spritebatchnode efficiently and now 1 spritebatchnode covers the 2 characters animation set. The FPS tried to get back to normal, but its still laggy at times. This worries me because my game design has more enemies to the game, meaning that it will have this issue in a bigger scale. So I believe that its because of my animation approach, its poor, and inefficient making my game run slow.

I have been trying to find the answer online with no luck, and I don't my approach is the best. I tried working some solutions by my own, but they end up in the same thing. THE ONLY, the only way I find how to reduce this problem is to make my sprites smaller, its not a big deal, but I wouldn't like this solution.

# Answer
> 1 votes
First, *are you running on the simulator or a real iOS device*? The device runs many times faster than the simulator. The simulator doesn't do hardware vertex processing. So the simulator slows down quite a bit with only a little load. If its slowing down on the simulator, that's not really an indication that it will be slow on an actual device at all.

Due to the way iOS's CADisplayLink works, iOS runs at either *60 fps* (maximum) or *30 fps*, or 15 fps (or slower). So if your app suddenly takes *just over 16.666ms* to process a frame, you're into the 30 fps category then.

I don't know Cocos2D, so I cannot tell you how to get back up to 60 fps (try compiling in release mode?)

Anyway, if you've been bumped down to 30 FPS, you might add **a lot** more stuff before being bumped down to 15 fps.

---
Tags: cocos2d-iphone
---


# Question
Title: Novice Mobile Game Developers | Publishing on our own or Publisher?
So we are almost done with our first indie game, developed on Android. We believe that the game has potential, our graphics guy is damn good so we have some good eye candy in our game.

Now we are thinking what should be our starting step? We can purchase the Google Play account and launch it on our own, but we aren't sure if we'd be able to advertise it well and get something big out of it.

Or we can contact a publisher, and talk about some deal.

Which one is better? What are the pros and cons of both, considering this is only our first game and we intend to make a lot more. Also considering that we're only students yet, currently in our senior year. We would love to generate some revenue out of it.

What are the best ways of contacting publishers? How do we approach them and deal with them?

Many thanks for your kind help!

# Answer
> 3 votes
For your first game, I would suggest self-publishing. If you get enough publicity and attention, you can do very well. It is viable to contact a publisher, though, if your game looks good and has good playing/replay value.

Some effective ways to market, if you self-publish:

* Write articles for gaming sites, such as indiedb.com, gamedev.net, etc
* Submit demos of your game to gaming sites
* Talk about it in your daily life. You would be surprised how much can be accomplished by word of mouth. (Just don't be too obnoxious.)
* Make a (Mobile-friendly) website
* Send copies to influential Web Personalities, such as Quill18, Rock Paper Shotgun, or others on YouTube ( or anywhere that could get you exposure)
* Post a video of the game (or two, you can make one as a trailer sort of thing, and one showing some of the features, with a voice overlay)

Publishers:

I would advise contacting one of two publishers, if you want to have them publish your game. Either contact Chillingo, a division of Electronic Arts (EA) that publishes Indie games for iOS, Android, and other platforms, or to try to get your game on Steam. Negotiate for a fairly good deal, if you can, and be able to make the publisher LIKE you. That usually helps.

Self-publishing vs using a Publisher:

Since this is your first game, presumably developed in your free time, some of these coming items will not apply yet, such as covering development costs. Later in your career, if you intend to keep on creating games as an indie studio, more of these things will.

Pros of Self-Publishing:

* 100% of the revenue goes to you, for whatever you need
* You own all rights to the game
* You retain full control over ALL aspects of your game

Cons of Self-Publishing

* Marketing your game is MUCH harder
* You will pay all costs for publishing, if any
* If the game isn't successful, you are responsible
* It is easier for you to lose money (esp if you need to cover major development costs)

Pros of Publisher deals:

* Usually the game makes more revenue than if self-published
* Advertising will be done more effectively by the publisher

Cons of Publisher deals:

* Publishers usually take most of the profits
* As an indie developer, publishers will not usually cover development costs
* You almost always do not keep ownership of the game
* A contract is usually required (Make sure that the publisher is not pulling one over on you, have a lawyer read it, it is OK to spend a bit of money here.)

Good luck! Hope this helps!

---
Tags: marketing, publishing, revenue
---


# Question
Title: Where to put Entity Death Events in a Component/System Design
Entities in my game are nothing more than a collection of components, tied together with an entityID. I have (near) data-only components, and systems that work on the data.

One of these components is `HitPoints`. It is one of the few components that has a little bit more than just data: it houses a `Dying` event that triggers from the `HitPointsSystem` when the hitpoints go below 0. One of the event listeners is my user interface, while an entity is selected, it listens to the current selection's `Dying` event. On-death, the entity is dis-selected. Having entities selected draws little circles around the selection. It works great... Right up until I have an entity without `HitPoints` that can still die.

I have a `Missile` in my game which does *not* have `HitPoints`, but it can be selected, and it can die. When a `Missile` is selected, my user interface recognizes that it does not have `HitPoints`, and therefore also does not have a `Dying` event, which later causes the draw loop to attempt to draw a "selected" *and* dead Missile, causing a crash.

You might guess that you could just add `HitPoints` to the `Missile` and everything would be fine, but my AI targeting system looks for enemy `HitPoints` because those are the only things it can damage. I don't want missiles to be targeted, and I don't want to add a special rule either.

So... if all entities can die (or be deleted), where do I place the `Dying` event? Should I be making a new component? Either a component for all things that can die (almost everything), or a component for AI targets? Or is there a better place to put an event like this?

# Answer
> 2 votes
I've read up a little bit since our conversation last night, because I was (still am) woefully inexperienced with this particular game architecture. One article I read was Mick West's preeminent talk/case study about using a component-only system. In it, he describes an effort to get rid of a badly written class hierarchy and instead use an entity manager.

One thing that jumped out at me: Mick was indicting classes...but he wasn't really presenting good evidence. He said that their team started with bad code, wrote good code, and solved their problems. That could just as easily have been "we had a terrible entity management system, and we replaced it with a good class hierarchy, and things improved." My point is that bad code is bad, good code is good, and any architecture can occupy either role.

I think the problem with your system is that it doesn't achieve the goals that Mick needed: encapsulation, no tight coupling, simple components that can be added freely.

By relying on `Hitpoints` to do too much, you've run into problems. They are at the core of your AI's targeting. Depending on their value, they fire an event. That event affects your user interface. You user interface affects your rendering, which checks `Hitpoints` again to see how to draw. You've got spaghetti.

What happening is that, in spite of using a component-only system, you still have brittle interdependent systems. You don't have encapsulation. You can't add new features to objects without breaking manager systems. You have to add redundant code to (ID value-only) entities, just to keep unrelated functions working. Which, according to Mick, is the original problem you were trying to avoid:

> the objects tended to be heavyweight. Objects had unnecessary data and functionality. Sometimes the unnecessary functionality slowed down the game. Functionality was sometimes duplicated in different branches of the tree.

I like your `Targetable` component, I think that's a step in the right direction. But you probably also need `Selectable`, `Dying`, `Render`...everything as a true single-purpose component. It will be challenging to maintain that stricture when those systems need to talk to each other (and real-world compromise is unavoidable, says Mick), but the alternative is to lose all that your entity system promised to give you.

# Answer
> 0 votes
As a temporary measure, I have created a `Targetable` component that I have added to all of the targetable entities, then I added `HitPoints` to the missile. My AI now targets only `Targetable` entities, and my UI can listen to the death events for my `Missile`. This feels like a half-measure. The next entity that comes along and is able to be selected and deleted will also need to have `HitPoints`, which could be wrong.

Perhaps in the long term, I need an Entity class that can store this? Or maybe every Component should have a death event.

---
Tags: c#, xna-4.0, component-based, events
---


title: XNA Multiple Key Input

text:
# Question
Title: XNA Multiple Key Input
I'm using the KeyboardState state way (if there are any others) of handling key presses for a PC game. It has been working fine for single key presses but now I am trying to handle multiple key presses at once.

I have it grab the newState at the top and then save it to the oldState at the bottom. I've tried it this way:

```
if (newState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.D2) && newState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftAlt))
{
    if (equipment_accessory2 != null)
        UseItem(equipment_accessory2, "Accessory 2");
}

```

And I've also tried:

```
Microsoft.Xna.Framework.Input.Keys[] currentPressedKeys = newState.GetPressedKeys();
bool altPressed = false, twoPressed = false;
for (int i = 0; i < currentPressedKeys.Length; i++)
{
    if (currentPressedKeys[i] == Microsoft.Xna.Framework.Input.Keys.LeftAlt)
                altPressed = true;
    else if (currentPressedKeys[i] == Microsoft.Xna.Framework.Input.Keys.D2)
                twoPressed = true;
}

...

if (altPressed)
{
    if (equipment_accessory2 != null && twoPressed)
        UseItem(equipment_accessory2, "Accessory 2");
}

```

Both ways work to a certain degree. The end result is that you're able to press alt and then a key between 1 and 5 to quick use a consumable. Normally you have skills in those slots so holding down alt makes the skills you have bound disappear and instead shows your quick use items.

The problem I'm having is that no matter what I have tried, the only way it works is that you have to hold 2 then hold alt. If you hold alt first and press/hold 2 it does nothing and doesn't work. I have spent 4 or 5 hours trying to figure out why it only works when you hold down 2 and then press alt. The problem with having it only work this way is if they have a skill bound to 2 then they're going to use the skill so the system is supposed to be to hold down left alt to swap the skill bar to the quick use bar.

I can't figure out why both ways I've tried doing multi key input aren't working when I press alt first.

EDIT: ok it must be something with my keyboard because alt+1 works but 2, 3, 4, and 5 don't work. EDIT2: restarted and 2-5 work now too, was something with my keyboard apparently.

# Answer
This should do the trick. You have to record last state to be able to compare 'alt' button state. If you compare it to last state, you can see if it's being held down. After you are sure, alt is being held down, you have to make sure that D2 was just pressed. You do this, by checking if in last state it was up and is now down.

I wrote this down in code, but i did not test it. Should work as is.

At top of your Game class:

```
private KeyboardState lastKeyboardState;
private KeyboardState currentKeyboardState;

```

In update loop:

```
lastKeyboardState = currentKeyboardState; // Set current state to last state, so we can compare states and see what has changed
currentKeyboardState = Keyboard.GetState(); // This gets the current state of all buttons

// If alt was down in last frame and it is still down, its being kept down
bool altIsDown = lastKeyboardState.IsKeyDown(Keys.LeftAlt) && currentKeyboardState.IsKeyDown(Keys.LeftAlt);

bool key2WasPressed = currentKeyboardState.IsKeyDown(Keys.D2) && lastKeyboardState.IsKeyUp(Keys.D2);

if(altIsDown)
{
    if(key2WasPressed)
    {
        if (equipment_accessory2 != null)
            UseItem(equipment_accessory2, "Accessory 2");
    }
}

```

Those two variables could be placed right in the IF's, but i separated em, to make it clear, how it's checked.
> 2 votes

# Answer
Its your use of `else` that is messing you up. The "else" (D2) is only checked if the Alt is not pressed. The reason it works when holding 2 down first, is because the next frame it senses the alt.

try:

```
for(I = 0; currentKeys.Length, I++)//how you syntaxed it
{
  if(curren...[i] == leftAlt)
  {
     altPressed=true;
  }
  if(curren....[i] == d2)//no "else" should be here
  {
    d2Pressed = true;
  }
}

```
> 1 votes

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