text:
How do I deal with different "types" of entities in Entity-Component-System model?
I have CollisionSystem which basically iterates through the array of PhysicsComponent and checks if there was some collision between two entities. But where should interaction code go? And how should I deal with different types of entities? (pseudocode below)
// in collision system
for(e1 in all entities) {
    for(e2 in all entities) {
        if(e1 == e2) continue;
        if(e1 collides with e2) {
            handleCollision(e1, e2);
        }
    }
}

...
// probably in collision system too?
void handleCollision(Entity* e1, Entity* e2) {
    if(e1 has DamageComponent) {
        if(e2 has HealthComponent) {
            e2->HealthComponent->
            reduceHP(e1->DamageComponent->damageAmount);
    //but what if some entities show "Hurt" animation or
    // do some other stuff specific for that type of entity?
        }
    }
    ... // other types of entities
}

What is bad is that this handleCollision code will have lots of if-else conditions as more and more types of entities emerge and the code will be hard to maintain. How can I deal with this?

Have you noticed in Halo 3 stuff bumps when a play approaches them? (like the big square crates, or those radio towers...) or anything moving (say grenade). That's because the physics system isn't bothering with them at all. When something goes near them they fall (they are slightly above the surface) and for computational simplicity rather than ray casting, the next frame is when the force up is applied to keep them out of the floor (or impulse actually) but anyway, that's why they bump.

There are many, many ways to approach this, depending on the needs of your game and what you want the API surfaces to look like. This is also not a problem that really has anything to do with entity systems. A physics API should maintain a list of physics object (often "rigid bodies"), detect, and resolve the collisions between them. The API can be a "system" in the common component-based parlance, or not. A physics object can be a physics component or not. It doesn't matter: the solution is the same.
You don't want the physics code itself to know anything about the interactions between specific objects, beyond the fact that they collided (and perhaps some metadata about the collision). Instead, design your physics API to support the notification of a collision to interested parties, who can subscribe to events on the physics API if needed. You can implement this behavior with the observer pattern. Thus you delegate the processing of the interaction elsewhere.
In whatever higher-level code deals with the interaction now (typically something more at the "game" level), you can employ techniques such as double-dispatch to resolve interactions between two runtime component types (normal dynamic dispatch in C++ and most languages is done only on a single parameter, the this pointer; double-dispatch is a way to perform dynamic dispatch on two parameter types, which is all you have varying in the case of two objects interacting).
Back in the physics system itself, you can avoid the n-squared problem of checking every rigid body against every other rigid body using spatial partitioning techniques. By dividing up your simulation space into distinct regions (for example using quad-trees or oct-trees, or even simple separation-of-axis approaches) reduces the problem space for detecting collisions by immediately discarding large numbers of objects that cannot possibly collide.

Thanks for your answer. Do I need to have some sort of DamagedBehaviour classes to deal with collisions when CollisionSystem notifies them that collision happened?

If you want. You could do it with or without such a system though.

Personally, I'd do something like this:
// in collision system
for(e1 in all entities) {
    for(e2 in all entities) {
        if(e1 == e2) continue;
        if(e1 collides with e2) {
            e1.sendMessage(COLLISION, e2);
            e2.sendMessage(COLLISION, e1);
        }
    }
}

//on the component that needs to handle a collision
void DamageComponent::handleMessage(MessageType msg, Entity* e) {
    if (msg == COLLISION) {
        if(e has HealthComponent) {
            e2.sendMessage(reduceHp, damageAmount);
        }
    }
}

void AnimationComponent::handleMessage(MessageType msg, Entity* e) {
    if (msg == COLLISION) {
        //...
    }
}

This requires a sendMessage method on the Entity class that sends on the message and parameter to each component that makes up the Entity. The Entity parameter on the handleMessage method should really be a void* so you can pass anything in.

But I want to have different collision responses. Does that mean I'll have different components for each?

Yes, and that's the point of component based entity systems. In the above example the DamageComponent's response to a collision is to damage the Entity it collided into. The AnimationComponent could play an animation. The logic for what response you get is in the choice of components, not hard coded in an if statement.

No, I mean do I need to have something like FurnitureDamageComponent and EnemyDamageComponent, etc. because different entities will react on collisions differently

It depends on exactly how 'different' you want entities to react. There's nothing to stop you making the DamageComponent configurable, but you need to take care you don't bundle every feature into a single component. How different to you see collision responses being?

I actually found a pretty good website recently that helped me.
http://afloatingpoint.blogspot.com/
This lets you test for derivations and whatnot. Personally I would detatch my physics code so that the component is simply a pointer to some data and that the index of that data can easily be indexed.
You could go GameComponent->PhysicsComponent (abstract)->BoxCollider ... etc. Then you just need to go with
         Entity->GetComponent<PhysicsComponent>()

to get the collider, or if you want a specific one you can check to see if you have
         Entity->GetComponent<BoxCollider>()

Also on your physics code you don't want to recheck specific pairings so your for loop could be different for a nice speed up. Also it is unlikely you want your callbacks to happen RIGHT when the collision happens. Maybe but I'd let my physics code finish up first so you don't destroy the cache and that way if you raycast or whatever all the colliders are resituated where they need to be.
    /*
        Want a continuous block of colliders for processing.
        Makes processing much faster.
    */
    vector<AABB> m_aabbColliders;
    vector<AABBCollider*> m_aabbComponents;

    Queue<Collision> m_collisionQueue;

    Collision collision;
    //No comparison necessary because when i is zero it evaluates as false
    for(auto i = m_aabbColliders.size();i;--i)
    {
       //No need to check i or greater then i because all collisions
       //combinations in that part of the list have been checked.
       //Since j will never equal i we can ignore having the if(j == i) clause here.
       for(auto j = i - 1;j < 0;--j)
       {
         //Physics Code
          if(Physics::AABBvAABBCollision(m_aabbColliders[i],m_aabbColliders[j],&collision))
          {
              collision.first = m_aabbComponents[i];
              collision.second  m_aabbComponents[j];
               m_CollisionQueue.push_back(collision);
          }
       }
    }

    //Let the physics engine deal with collisions before you take call backs.
    //To resituate collided objects.

    //Collisions are DONE now deal with callbacks to pass that info to
    //Entities that need to know.
    Message collisionMessage;
    for(auto i = m_collisionQueue.size();i;--i)
    {
       collisionMessage = Message(m_collisionQueue.pop());
       collisionMessage.asCollision().first->SendMessage(MessageType::Collision,collisionMessage);
       //Maybe swap first and second here depending on
       //if you want your engine to have the collision message
       //have first be itself always or something.
       collisionMessage.asCollision().second->SendMessage(MessageType::Collision,collisionMessage);
    }

 //DamageComponent Code

 void DamageComponent::RecieveMessage(MessageType type,const Message& msg)
 {
  switch(type)
  {
     case MessageType::Collision:
         Message dmg = Message(dmg_amount);
         msg.asCollision().second->SendMessage(MessageType::DealtDamage,dmg);
         break;
  }
}

void HealthComponent::RecieveMessage(MessageType type,const Message& msg)
{
    switch(type)
    {
      case MessageType::DealtDamage:
        this->ChangeHealth(-msg.asInt());
        break;
    }
}

void HealthComponent::ChangeHealth(int amount)
{
   if(m_health != m_maxHealth && m_health + amount >= m_maxHealth)
   {
      m_health = m_maxHealth;
      SendMessage(MessageType::HealthFilled);
   }
   else
   {
      m_health += amount;
      if(m_health > m_maxHealth) m_health = m_maxHealth;
   }

   if(m_health <= 0)
   {
      Message msg = Message(playerComponent);
      SendMessage(MessageType::PlayerDeath,msg);
   }
}

//On the Player script you can have it recieve the event then remove itself from   queues and setup respawn and all that other stuff.

As you can see this can get really interconnected but still be completely encapsulated in individual components.


text:
Bullet: Get steepness or slope between positions
In a CharacterController object, there is
setMaxSlope(btScalar slopeRadians)
The max slope determines the maximum angle that the controller can walk up.

But how about knowing it in advance? Like check if the position where the character will move next is walkable (i don't know the correct word) or not? Is that possible? Any suggestions on how should I go about this?

You could sense ahead of your characters movement with a ray-cast or a bunch of ray-casts depending on your desired accuracy.
Then calculate the slope angle in front of your character by using the polygon's slope directly or in case of multiple ray-casts, calculate some approximation.
I did this when I first started out with a Kinematic Controller. But eventually, the controller had too many shortcomings and I implemented my own as I describe here:
https://stackoverflow.com/questions/25605659/avoid-ground-collision-with-bullet/25725502#25725502

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Particle system: BlendMode of particle's draw call
I noticed by reading some tutorial around the web, that when dealing with particle systems, you can both use these approces:

Black background on the single particle and additive mode as blending mode for drawing
Transparent background on the single particle and alpha blend mode for drawing.

What are the differences between the two approces?

I think the main difference is that the alpha blend version will require particle sprites to have an alpha channel. So a bit more memory used perhaps?

Additive will washout to pure white if you have a high enough level of overdraw (which is very small). Proper alpha blending is not going to have this problem, but it also requires you to sort your particles.

Transparent background on the single particle and alpha blend mode for drawing.

This should be the most common method for general particles. The problem of this method is you have to sort the particles and rendering them back-to-front to get the alpha blending works correctly. It would bring a heavy burden on CPU when there is a lot of particles. And if the particles are not simple billboards and may intersect with each other, it may be unsolvable with simple sorting.

Black background on the single particle and additive mode as blending mode for drawing

You don't need to sort the particles, as the order of particles doesn't matter in additive blending. However, this method only works for a smaller set of effects, like fire.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Make the player run onto stairs smoothly
I have a 2D Platform game, where the player Always runs to the right, but the terrain isn't Always horizontal. Example:

I implemented a bounding-box collision system that just checks for intersections with player box and the other blocks, to stop player from running if you encounter a big block, so that you have to jump, but when I put stairs, I want him to run smoothly just like he is on the horizontal ground. With the collision system you have to jump the stairs in order to pass them!
I thought about generating a line between the edges of the stairs, and imposing the player movement on that line... What do you think? Is there something more clever to do?

If you're able to rotate the boundingboxes, I would've put a 45 degree rotated box at the player's feet and combine it with one non-rotated box to represent the rest of the body. That could make the player automatically slide over anything small enough.
Though, that would probably cause some clipping with the player model and the stairs.
Another idea is to put one boundingboxes from the character's head to kness with higher width than the box of the character.
When the player collides with something which the box 'A' does not, you can move the player ontop of what it collided with
_________________
|    |     |    |
|    |     |    |
|  A | pla | A  |
|____| yer |____|
     |     | _________________________ <- step
     |     | |
--------------------------------------------- <- ground

There are three general approaches to dealing with stairs in video games:
The "Mario" approach is that you must jump to get up stairs.
The "Castlevania" approach is that moving up/down stairs is a different sort of movement;  you must press 'up' on the controller, and a special "stair-climbing" animation is played to traverse the stairs.  A variant of this is the "Resident Evil" approach, where moving up/down stairs is treated as a complete cutscene that plays when the player presses an interaction button;  no interactive stair-climbing is permitted whatsoever.
The "Almost Everyone Else" approach is the one that you mentioned:  treat the stairs as if they were actually a ramp.  Depending on what sort of game it is, you may wish to place the ramp at different heights relative to the stairs.  Typically in a 2D game, the "the stairs are actually a ramp" trick is less noticeable to the player if the ramp is level with the bottom corners of each stair step, while in a 3D game it's typically less noticeable if the ramp is level with the top corners of each step.  (as in a 2D game it's easier to notice if a character's feet are floating above the ground, and so you want to minimise that, whereas in a 3D game it's easier to notice if a character's feet are clipping through the ground, and so you want to minimise that).

Great remark on float/clipping on different graphical standpoints.

Your information is quite a bit wrong. Only in the old mario games you have to jump to get up stairs. But I guess that's obvious. But resident evil definitely also had stairs that can be climbed interactively!

Most of the methods I've encountered have already been stated above -- but there's still one more that hasn't been mentioned. When the player encounters a vertical obstacle that's short enough (say, 1/3 their hight), simply put them on the top. Minecraft and the Source engine for example take this approach in that kind of situation. Additionally, this method allows you to still use pure AABB for all of the physics while not putting the player through the pain of constantly having to jump up stairs.

Would be nice if you could explain how to detect such obstacles.

I'm currently working on a similar part of an engine, and the way I dealt with stairs/slopes is by counting the transparent pixels in my ramp texture and offsetting the player's object by the amount found.
It is similar to the idea of the height map that is detailed in this article:
http://info.sonicretro.org/SPG:Solid_Tiles#Slopes_And_Curves
I imagine that's really what you would be looking to do, and you can choose to play a different animation that plays according to the ascension of the stairs.
There is also a good overview of the different slope concepts in this article:
http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/


text:
Player's camera, how to obtain smooth movement
In a 2D platformer, I have a player that can move both horizontally and vertically. I also have a camera that moves in relation to player. In every update I do this:
public void RepositionCamera()
{
   // For the example I don't consider world rectangle bounds
   current_camera.Position =
      new Vector2(
         player_.Position.X - 250,
         player_.Position.Y - 100));
}

The problem here is that when I press very rapidly "left-right-left-rigth..." the camera does a very annoying effect, it seems an eartquake.
I think this is due to the strict relation to player's position and camera's position.
This is just an example, it is annoying also when climbing onto stairs because every step I force the player's Y up to the step height, so the camera does the same thing!
How can I solve this? How can I edit my RepositionCamera() to be less strict about moving itself?

I solved by doing this:
   player_camera_.Position = new Vector2(
            MathHelper.Lerp(player_camera_.Position.X, player_.Position.X - 250, 0.08f),
            MathHelper.Lerp(player_camera_.Position.Y, player_.Position.Y - 100y, 0.08f));

The reason the camera shakes is most likely because of it is not being repositioned at the right time, so it lags behind one frame.
Example:
HandleInput() - right
UpdatePlayer() - move to right
Draw() - player after moving to right
RepositionCamera() - set camera to player position.

The world had already been rendered when RepositionCamera is called, and the player is always ahead of the camera. It could be the way around also.
I'd suggest you fix that first, but here's an example of moving the camera smoothly:
Vector2 delta = player_.Position - current_camera.Position; //Distance from player to cam
current_camera.Position += delta * 0.1 //Move the camera by 10%


text:
How do I implement space partitioning in entity component system?
My systems work on components without needing to now anything about entities. I want to implement simple grid partitioning, so each entity will be given a cell based on its current position. But how will systems know which components to update and how? For example: CollisionSystem must check collision between each components within a cell, but CollisionComponents must be somehow attached to the grid for system to know what collision to test, which doesn't seem like a good solution. What should I do?

Why does it not seem like a good idea? ECS is just one tool; if it doesn't work for the problem you're trying to solve, find a different tool.

ECS does not mean systems cannot interact. If you have one partitioning system the physics system can request all entity id's from a single cell and check which of these ids are in its own system.

Artificial intelligence components (for example) must know the state of the world in order to make decisions: There is nothing inherently wrong with letting a component have access to outside world state.
However, collision detection is typically (not always) handled by a function that sits outside of the elements to be collided. This is a matter of scope / context. In order to reduce coupling, which seems to be your intent, it is better to have one of the supersystems which already have access to all entities (bodies), apply the collisions. This prevents entities  from having to know about one another, and it also allows fine control over the ordering of collision detection and resolution, which is crucial.
So, you have your game loop. Somewhere in there you have a phase where you're processing collision detection and resolution. The wise choice would be to factor that out either into a separate function or even a whole separate class, depending on your language and architectural preference.
Given that you desire spatial partitioning over your world space, I would suggest implementing a discrete class CollisionManager. Therein, create your partitioning structure. You could add / remove entities to CollisionManager at creation / expiry of those entities, and most importantly, call CollisionManager.update() on each global update, ensuring that everything -- both moving between partitions (based on entity translations performed just  prior via other subsystems) and testing for and resolving collisions within partition locales -- is resolved compactly via a single method call.
As for your entity components associated with physics, the only purpose they serve here is to supply their respective positions and bounds information to CollisionManager.

@Quonux Small things amuse small minds, eh?


text:
Converting a GameObject method call from UnityScript to C#
Here is the UnityScript implementation of the method i use to generate a randomly tiled background, the problem i'm having relates to how to translate the call to the newTile method in c#, so far i've had no luck fiddling... can anyone point me in the correct direction?
Thanks
#pragma strict
import System.Collections.Generic;

var mapSizeX : int;
var mapSizeY : int;
var xOffset : float;
var yOffset : float;

var tilePrefab : GameObject;
var tilePrefab2 : GameObject;

var tiles : List.<Transform> = new List.<Transform>();

function Start () {
    var i : int = 0;
    var xIndex : int = 0;
    var yIndex : int = 0;
    xOffset = 2.69;
    yOffset = -1.97;

    while(yIndex < mapSizeY){
       xIndex = 0;
       while(xIndex < mapSizeX){

                var z = Random.Range(0, 5);

                if (z > 2)
                {

                 var newTile : GameObject = Instantiate (tilePrefab, Vector3(xIndex*0.64 - (xOffset * (mapSizeX/10)), yIndex*-0.64 - (yOffset *  (mapSizeY/10)), 0), Quaternion.identity);
                 tiles.Add(newTile.transform);
                 newTile.transform.parent = transform;
                 newTile.transform.name = "tile_"+i;
                 i++;
                 xIndex++;

                 }

                 if (z < 2)
                {

                 var newTile2 : GameObject = Instantiate (tilePrefab2, Vector3(xIndex*0.64 - (xOffset * (mapSizeX/10)), yIndex*-0.64 - (yOffset *  (mapSizeY/10)), 0), Quaternion.identity);
                 tiles.Add(newTile2.transform);
                 newTile2.transform.parent = transform;
                 newTile2.transform.name = "Ztile_"+i;
                 i++;
                 xIndex++;

                }

       }

       yIndex++;
    }
}

C# Version [Fixed]
using UnityEngine;
using System.Collections;

public class LevelGen : MonoBehaviour {

    public int mapSizeX;
    public int mapSizeY;
    public float xOffset;
    public float yOffset;

    public GameObject tilePrefab;
    public GameObject tilePrefab2;

    int i;

    public System.Collections.Generic.List<Transform> tiles = new System.Collections.Generic.List<Transform>();

    // Use this for initialization
    void Start () {

        int i = 0;
        int xIndex = 0;
        int yIndex = 0;
        xOffset = 1.58f;
        yOffset = -1.156f;

        while (yIndex < mapSizeY)
        {
            xIndex = 0;
            while(xIndex < mapSizeX) {

                int z = Random.Range(0, 5);

                if (z > 5)
                {
                    GameObject newTile = (GameObject)Instantiate(tilePrefab, new Vector3(xIndex*0.64f - (xOffset * (mapSizeX/10.0f)), yIndex*-0.64f - (yOffset *  (mapSizeY/10.0f)), 0), Quaternion.identity);
                    tiles.Add(newTile.transform);
                    newTile.transform.parent = transform;
                    newTile.transform.name = "tile_"+i;
                    i++;
                    xIndex++;

                }

                if (z < 5)
                {
                    GameObject newTile2 = (GameObject)Instantiate(tilePrefab, new Vector3(xIndex*0.64f - (xOffset * (mapSizeX/10.0f)), yIndex*-0.64f - (yOffset *  (mapSizeY/10.0f)), 0), Quaternion.identity);
                    tiles.Add(newTile2.transform);
                    newTile2.transform.parent = transform;
                    newTile2.transform.name = "tile2_"+i;
                    i++;
                    xIndex++;
                }

            }
            yIndex++;
        }

    }

    // Update is called once per frame
    void Update () {

    }
}

What errors are you actually getting?

I'm sorry i should have included that in the OP
"Object reference not set to an instance of an object"
Which just now i've managed to fix by casting it to type GameObject, the code now runs without errors but doesn't generate my terrain

I think the problem may be me not understanding how to create the GameObjects repeatedly each iteration like i can in the .js

Okay, i've fixed it after tinkering... Since i can't answer my own question, i've put comments on the edit :)

Grand, I'm separating your questions answer out so we can mark the question as answered, also your formatting is far too long to be read easily, you overwrote it in my previous edit of your question so I'm editing that in as well.

Please follow site etiquette by doing as @blue suggests and accepting his/her answer. Thanks.

So we can mark it as answered I've reformatted the details you have put up. Can you please revert your changes in your question so future viewers can see what changes were made if they have the same issue.
Also I noticed you have a lot of logic redundancies (like your if (z>5) and if (z<5)) as they can be condensed into an if(){}else{} statement with a smaller random range, considering z is used for nothing but a Rand comparison.
C# Version:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class LevelGen : MonoBehaviour {

    public int mapSizeX;
    public int mapSizeY;

    public GameObject tilePrefab;
    public GameObject tilePrefab2;

    private float xOffset;
    private float yOffset;
    private int i;

    public List<Transform> tiles =
        new List<Transform>();

    // Use this for initialization
    void Start ()
    {
        int i = 0;
        int xIndex = 0;
        int yIndex = 0;
        xOffset = 1.58f;
        yOffset = -1.156f;

        while (yIndex < mapSizeY)
        {
            xIndex = 0;
            while(xIndex < mapSizeX)
            {
                Vector3 tilePosition =
                    new Vector3(xIndex * 0.64f - (xOffset * (mapSizeX / 10.0f)),
                                yIndex * -0.64f - (yOffset *  (mapSizeY / 10.0f)),
                                0f);

                GameObject newTile =
                    (GameObject)Instantiate(tilePrefab,
                                            tilePosition,
                                            Quaternion.identity);

                int z = Random.Range(0, 3);
                if (z > 1)
                {
                    tiles.Add(newTile.transform);
                    newTile.transform.parent = transform;
                    newTile.transform.name = "tile_"+i;
                    i++;
                    xIndex++;
                }
                else
                {
                    tiles.Add(newTile.transform);
                    newTile.transform.parent = transform;
                    newTile.transform.name = "tile2_"+i;
                    i++;
                    xIndex++;
                }
            }
            yIndex++;
        }
    }

    // Update is called once per frame
    void Update ()
    {
    }
}


text:
When to get input state: multiple times or one time in a static class?
Let's say I have these classes:

Player

Here I want to make the player jump:
  current_state_ = Keyboard.GetState();
  if ((current_state_.IsKeyDown(Keys.Space) || current_state_.IsKeyDown(Keys.Up))
       Jump();

Intro scene
GameOver scene

Here I just want to give the possibility to skip those scenes:
  current_state_ = Keyboard.GetState();
  if ((current_state_.IsKeyDown(Keys.Space) || current_state_.IsKeyDown(Keys.Up))
       SkipScene();

My question is what is usual done:

"Asking" for input in every class, or make a static class that asks for input every update, and then you get that value?
public static class InputHandler
{
    private static KeyboardState current_state_;

    public static bool IsSpacePressed()
    {
        return current_key_.IsKeyDown(Keys.Space);
    }

    // Others

    // To be called in game's main loop
    public static void Update(GameTime gametime)
    {
        current_key_ = Keyboard.GetState();
    }
}

I'm worried about that because I thought (don't know if it is correct!) that maybe it is wrong to ask multiple times per update for input.

Generally speaking, static properties are a no-no in this case. They should only be used for utility functions (Vector3.Lerp), or for read only variables that will be identical for all instances of a class (Vector3.UnitX).
They introduce issues when trying to synchronize resources because of their nature (anything can access them, so several objects can attempt to update at the same time), and looking up static variables has a significant performance overhead. They also introduce a slippery slop when programming - once you start using them, the longer you go on for, the harder it is to stop.
I would suggest creating one local instance of the keyboards current state in your games main Update method as a local variable (local scope allocation and deallocation are slightly faster than accessing a global variable) and passing it to your Player, IntroScene and GameOverScene classes via a seperate paramater in their update call. This means instead of accessing some global static variable somewhere, you're accessing a local variable variable, which exists in the same scope (local scopes get searched first for variables before global scopes). Also, it means you only fetch the keyboard state once per update, further saving on performance. Given the number of update calls a second, a little bit of performance gain can go a long way
However, it does boil down to your preference in the end. If you feel statics are the best way to go, then who are we to stop you?
Some further reading, if you are interested.
http://forum.unity3d.com/threads/186915-Declaring-a-Variables-Locally-Vs-Globally-Effect-on-Performance
https://stackoverflow.com/questions/9924223/static-vs-non-static-class-members


text:
SpriteBatch, trying to reduce draw calls
This my main draw call:
       Matrix Camera_transformation = player_camera_.GetTransformation();

        // Background - AlphaBlend
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera_transformation);
        background_.Draw(spritebatch);
        spritebatch.End();

        // Particles (of a player power, I want them behind him!) - Additive
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null, Camera_transformation);
        player_.DrawParticles(spritebatch);
        spritebatch.End();

        // Player - Alpha Blend
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera_transformation);
        player_.Draw(spritebatch);
        spritebatch.End();

        // Hub/Ui - Not to be influenced by the camera, but always on top
        spriteBatch.Begin();
        UI.Draw(spritebatch)
        spriteBatch.End();

Is there a way to reduce the number of calls here?
If my particle system didn't need an additive drawing, I would have merged the first three calls, but I can't. Is there something I am missing about spritebatch ordering?

What are you trying to achieve here? A performance improvement? Or do you literally want to reduce the number of C# method calls? Because the code you have there is basically optimal for performance, as far as SpriteBatch internals go.

I would like to achieve better performances. I tried the suggestion below, but after profiling several times, I found it gets worse performances.

Note that profiling this kind of thing can be tricky - for example: is it the CPU or GPU slowing you down? As I said, at this stage you've basically maxed-out the performance for SpriteBatch (providing every particle you draw uses a single texture - see here). To improve performance, you have to go beyond SpriteBatch. If the CPU is slowing you down (and it probably is), perhaps you need to offload onto the GPU (rough example here).

Does SpriteBatch have support for premultiplied alpha blending? This lets us combine additive and standard alpha blending into a single formula, so they can be drawn together in a single batch or even mixed within a single sprite.

Changing the SpriteSortMode to Immediate is faster in the cases when the overhead of creating new batches is more signifigant than the time saved by batching. If this is the case in your situation the below will be faster. While the mode is immididate you can alter the GrahpicsDevice's state and it will impact subsiquent draw calls.
    Matrix Camera_transformation = player_camera_.GetTransformation();

    spritebatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null,
        null, null, null, Camera_transformation);

    // Background - AlphaBlend
    background_.Draw(spritebatch);

    // Particles (of a player power, I want them behind him!) - Additive
    GraphicsDevice.BlendState = BlendState.Additive;
    player_.DrawParticles(spritebatch);

    // Player - Alpha Blend
    GraphicsDevice.BlendState = BlendState.AlphaBlend;
    player_.Draw(spritebatch);
    spritebatch.End();

    // Hub/Ui - Not to be influenced by the camera, but always on top
    spriteBatch.Begin()
    UI.Draw(spritebatch)
    spriteBatch.End();

Uh... the only time Immediate mode is faster is when you've only got a couple of sprites per batch. So unless that particle system has, like, three particles in it, you're going to want to use Deferred.


text:
How do you lock the camera down in ZBrush?
I'm trying to sculpt a tileable mesh on a flatplane and I keep inadvertently moving the camera when I go off canvas. Is there a way to lock the camera in place?

I don't think this is really gamedev related?

Zbrush is used in game development...

So is literally everything.

You can save a camera angle using
Document>ZApplink properties> Then either choose front or Cust1
If you accidentally move your camera just navigate back to ZApplink properties and choose the camera you saved, it will snap the camera back to the saved position.


text:
How to achieve a Gaussian Blur effect for shadows in LWJGL/Slick2D?
I am currently trying to implement shadows into my game, and after a lot of searching in the interwebs I came to the conclusion that drawing hard edged shadows to a low resolution pass combined with a Gaussian blur effect would fit best and make a good compromise between performance and looks - even though theyre not 100% physically accurate.
Now my problem is, that I dont really know how to implement the Gaussian blur part. Its not  difficult to draw shadows to a low resolutions buffer image and then stretch it which makes it more smooth, but I need to add the Gaussian blur effect.
I have searched a lot on that and found some approachs for GLSL, some even here, but none of them really helped it.
My game is written in Java using Slick2D/LWJGL and I would appreciate any help or approaches for an algorithm or maybe even an existing library to achieve that effect.
Thanks for any help in advance.

Maybe I misunderstand the question but calculate a new image from your old one using a kernel that smooth out the values. Or is there some other part that hinders you?

I tackled almost an Identical problem about a year ago. Since then I've figured out how to add gaussian blur to create better shadows. I'm assuming you're starting from a point like this: Shadow Blog Post, Image of Shadows With No Blur. And this is what you're after Image of Shadows WITH Blur.
My lighting system code that included shadows can be found here: Lighting Manager. I ended up using a Shader "Wrapper" by Jeremy Klix here: Shader Wrapper.
The shaders I used are here: Shaders. Take a look at the bassicBlur.vrt, blurHorz.frg and blurVert.frg. Combined they are a simple 2 pass (X then Y) gaussian blur. I define the 2 (horizontal and vertical) shader objects around line 66. Then during rendering, I use the shaders around 135. The shader takes two parameters: radius of the blur and the resolution of the rendered area. The idea is that you:

Enable the shader
Enable a multiple blend function
Draw the shadow map
Revert the blend function
Disable the shader

Let me know if you'd like more details.

The good news is that constant width Gaussian filter is separable thus you can gain good performance even for large kernel sizes, i.e this cuts the computation from the naive O(n^2) cost down to O(2n). The separable Gaussian filter is implemented by having two passes over the image: First performing 1D horizontal Gaussian blur, followed by 1D vertical Gaussian blur. This is pretty much the standard way to implement Gaussian filter nowadays. Here is an explanation how to implement it in GLSL,


text:
Key Handling mechanics
I am new to game development and am working on my first game using OpenGL and C++.
I have a game class which handles everything necessary in an update() function.
Now i want to handle keyboard inputs. I use GLFW which supports key callbacks. However i wonder how to deal with inputs. Should i record the keys pressed and poll on it the next time my game updates or should the callback immediately perform the necessary actions? And why?
Thanks :)

It's far easier to control how your game controller acts if you take any asynchronous key inputs and store them away until the update loop can get to them.
First reason is that the update function may change conditions before the key is handled.  For example: I press fire.  If handled immediately you would create a fire action, but in update handling it could be that you're declared dead and unable to fire.
Second reason is that let's say you quickly press two keys, go left and go right.  If handled immediately that could fire off all sorts of secondary actions like animation changes, but if handled at update you can parse all the inputs and intelligently decide what the final outcome is and avoid lots of extra work.
Corollary to second reason is that combination keys are now easily handled, say Left + Up which would normally be handled by two separate callbacks for left and then up are now parsed by update as an entire action that means go diagonal.

As pointed out in the comments, I have discovered that this version only works if using LWJGL, the java port of OpenGL.
Use OpenGL's Keyboard class.
Please note that I use LWJGL so the syntax may be different from yours.
while (Keyboard.next()){
            if (Keyboard.isKeyDown(Keyboard.getEventKey())){
            String app = Keyboard.getKeyName(Keyboard.getEventKey());
            if (!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){
                app = app.toLowerCase();
            }
            if (app.length() != 1){

            }else{
            //if (app != null && app != "" && app != " "){
                TextDemo.user.append(app);
                System.out.println(app);
            }
            }
            //}
        }

Keyboard.next() checks if a key has been pressed down or released.
I check if the event key is down. The event key is the key that is involved in the press or release, and I want to see that it has been pressed, not released.
The output is capitals, so if shift is down I keep it capitals, if it is not then I make it lowercase. I have yet to implement caps lock.
And the rest of the code is checking that it is not something like the spacebar or shift (More than 1 character), and if it is not, then append it to a string which I draw onto the screen in another piece of code that I have not shown above.
You can also use Keyboard.getEventCharacter(), however in my experience this returns a weird box character which can be annoying. Experiment with it :).
Hope this helped!
Edit: The above was mainly for typing strings. You can use the following code as well:
if (Keyboard.isKeyDown(Keyboard.KEY_YOURKEYHERE));
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE));

Opengl does not have a keyboard class. This seems to be something that lwjgl implemented.

@Eejin Dammit!! >:(

It depends. Personally I would look at key presses in a constant part of the loop instead of performing the action as soon as the key is pressed. But it may be beneficial to you to perform the actions as soon as the key press comes in. Is there anything that need immediate processing in your application?


text:
How can I manage entities(in entity component system) using Lua scripts?
Suppose I have a code like this in C++
// Game.cpp
Entity* hero;
Entity* witch;
... // entity initialization

if(/player near witch/) {
    if(hero->get<HealthComponent>()->getHealth() < 100) {
        say("Let me help you");
        witch->get<GraphicsComponent>()->setAnimation("witch.heal");
        hero->get<HealthComponent>()->setHealth(100);
    }
    else {
        say("Go away!");
    }
}

Suppose I want to put this code into Lua script, so I make an "interact" function in C++
void interact(Entity* first, Entity* second);

And call it like this:
interact(witch, hero);

Then I can call lua script, which gets first and second entity IDs and does something like this:
-- Script.lua
function interact(firstId, secondId)
    if(getHealth(secondId) < 100) then
        say("Let me help you")
        setAnimation(firstId, "witch.heal")
        setHealth(secondId, 100)
    else
        say("Go away")
    end
end

And then I can define wrapper functions in C++ like this
void setAnimation(int firstId, const std::string& animationName) {
    Entity* e = entities[firstId];
    e->get<GraphicsComponent>()->setAnimation(animationName);
}
// etc.

and call it from Lua. But this gets quite troublesome as I need to write lots of binding and wrapping(like "setAnimation") functions. Is there any other methods to control entitity behaviour using Lua?

Find (or write) a library that automates the binding as much as possible. Do a search for "lua c++ binding" and you should find a lot on the subject.

@glampert Maybe my question was not exactly clear,(I've edited my question) but my main question is: should I try to find a way for Lua to know about components or should I write wrapping functions like "setAnimation" in my example?

Writing binding functions gets tiresome pretty fast, and is error prone. There are two ways I can think of on how to improve this:
1) Use some Lua wrapper code that creates the interface functions you need. I
did see on your blog that you have used LuaWrapper. Not sure how much support that lib have but there are others that use templates to create the binding functions. For my own project, I wrote my own system that also have the name LuaW. This is an example of what my code looks like. All objects are managed (created/destroyed) in the C++ code:
C++ side:
LuaW_Class<CameraComponent>( scriptEngine->m_pkState, "CameraComponent");
LuaW_ClassFunction(scriptEngine->m_pkState, "CameraComponent", "GetName", &CameraComponent::GetName);
LuaW_ClassFunction(scriptEngine->m_pkState, "CameraComponent", "GetCamera", &CameraComponent::GetCamera);
LuaW_ClassFunction(scriptEngine->m_pkState, "CameraComponent", "AddTestRenderer", &CameraComponent::AddTestRenderer);

LuaW_RegisterGlobal<World>(scriptEngine->m_pkState, "World", m_world.get());

Lua side:
local cament = World:MainScene():CreateEntity("blueprints/camfront.blueprint", Vector3:new(0,0,0) )
camcomp = cament:GetComponent("CameraComponent")
camcomp:AddTestRenderer()

By using a wrapper lib like that you can stop writing binding functions, unless of course you wish to do something special like returning multiple values.
2) The second way is to keep the components and as much stuff as possible in Lua code. So most of your game will be in Lua and only the functions you really need to write in C++ will require a binding function.

Thanks for your answer! Two more questions: 1)Is my method of working with entities okay? I think it's easier to make some wrapper functions (like "setAnimation" in my example) than make a way to access components for each entity. Or should I do it the way you have shown?
2) You create entity in Lua in your example. How can you access it in C++? What if you have hundreds of entities? Is it possible to create them in Lua while still having fast access to them in C++?

1: I think both ways are fine. You can also try a mix of both by writing a custom wrapper generator. One that generate functions like you already have that get's the component and call the function. That way you do not need to expose the components to lua code. It's the next step i will look into for my own LuaW code. 2: Entitys are always created in C++ and returned to lua as userdata so it's no problem handling them in C++. I use MainScene():DestroyEntity() to remove them.


text:
Where to implement textures for tiles?
So I just learned the basics of Java and was ready to try to create a protoype game in the style of Civ. So a tile&turn based game.
I created an enum for the different tiles:
public enum TerrainTile{

 WATER(1), GRASSLAND(1), HILL(2), FORREST(2), BLANK(99);

private final int id;
private final int moveCost;
private boolean hidden = true;

private TerrainTile(int moveCost) {
    this.id = this.ordinal();
    this.moveCost = moveCost;
}

I made a JFrame:
public class MainFrame extends JFrame {

private MapPanel pnlMap;

public MainFrame(Terrain map) {

    setTitle("MyGame");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    getContentPane().setPreferredSize(new Dimension(500, 500));

    pnlMap = new MapPanel(map);
    pnlMap.setPreferredSize(new Dimension(500, 500));
    add(pnlMap);

    pack();
    setLocationRelativeTo(null);

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {

            BufferedImage mapImg = null;
            try {
                mapImg = ImageIO.read(MainFrame.class.getClassLoader().getResourceAsStream("frames/resources/map2.png"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            Terrain map = new Terrain(mapImg);
            System.out.println("Terrain created:");
            map.printTerrain();

            JFrame frame = new MainFrame(map);
            frame.setVisible(true);

        }

And a JPanel for the map:
public class MapPanel extends JPanel {

private final Terrain map;

public MapPanel(Terrain map) {
    this.map = map;
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

}

when I wasn't sure where to save the textures for the tiles.
Should I just read out the array of the map and do a switch statement to define inside the MapPanel class which texture to draw or should the textures better be implemented inside the enum?

Take a look at this.  It's common to have a single image for all your tiles and draw a different part of it at rendering.  You can then draw your tiles like this :
int mx = tileId % numberOfTileCols;
int my = tileId / numberOfTileRows;

graphics.drawImage(image, x, y,
    x + tileWidth, y + tileHeight,
    mx * tileWidth,
    my * tileHeight,
    mx * tileWidth + tileWidth,
    my * tileHeight + tileHeight, this);

This way you can store a single texture in the MapPanel but get rid of the huge switch statement.


text:
Issues using real names in a soccer player game
Is illegal to use the real player and team names in a game? When I say game could be and desktop, mobile or fantasy game.
If is illegal, is ok to change a little bit names? Instead of using Messi could I use Messsi (or something similar)?
All gambling and statistics soccer websites have permissions to use those names?
Thanks!

Also of legal issues around using real players names and emblems

Also of does it require any license to use soccer players and teams names in...

Also of soccer game only with national team names what about player names?

Also of Can I put real people in my game?

Also of Using real football (soccer) names from the past?

And incidentally, why do we only get this question about soccer?  (and why do we get it so frequently in that domain?)  We've never had people asking whether they can use real names in a game about basketball, about football, about baseball, or about hockey.  We've never had someone ask if they can use real names in a game about figure skating, about curling, about bobsledding, or about dressage.  Why is it always soccer?

Thanks for the links! I asked because we are in the middle of the FIFA World Cup.

No, not generally. Not without permission.
Gambling and stats sites are a different case. There's a difference between using someone's name in a factual article about that person and using their name and likeness in a FIFA-like game.
Minor spelling variations are not enough, otherwise we'd all be playing Lorrd of teh Ringz games.

Your answer would be more complete if you made the difference between using a name for pure information and using a name for a commercial purpose. Other than that, +1.

@AlphSpirit: I touched on it, but honestly I don't know where the line is. I Am Not A Lawyer and all that jazz. Typically, I prefer to just stay so far on the safe side of the line that I can barely even see it anymore. Be original and make your own game/world/characters/sport, IMHO. :)

Thanks! But what is the difference using the name in a game or using it in a gambling site? For example, this website: http://tools.fifaguide.com/player.php?id=1694519617

@JoseDaniel why do you think this site is legal? or that it doesn't have a license? You don't know, most likely, so it's pointless to compare yourself to that.

Celebrities have the rights of publicity in their own likeness which means that you're not allowed to make a profit off of something with their name or face without their permission.  You could make a game that uses characters that are clearly meant to represent famous athletes (as long as the difference is enough to protected under the fair use policy and it's not simply a caricature).
I would strongly suggest that if you make a game, you should use all of your own original content because it's much better to make a less popular game than to be sued by your favorite soccer players.


text:
Set value in an array[3], that the sum of all three values is always 1.0
So I'm working on a Civ like game right now and want to have a setting how taxes are split in gold income, science and luxury goods.
private double[] rate = new double[] { 0.4, 0.6, 0.0 };

now I wanted to add a methode to change one of the values to a higher or lower value but maintain the overall sum of 1.0 (100%)
but I'm stuck here with how to take or add values evenly from the other two rates
    public void setRate (int index, double r) {
    if (r < 0.0) {
        throw new IllegalArgumentException("Invalid Rate");
    }

    double diff = r - rate[index];
    if (diff > 0) {

        // ?

    } else if (diff < 0) {

        // ?

    }
    rate[index] = r;
}

EDIT for amitp:
public void setRate (int index, double r) {
    if (rate[index] = 1.0) {
         for (int i = 0; i < 3; i++) {
              if (i != index) {
                  rate[i] = (rate[index] - r) / 2;
             }
        }
    } else {
        for (int i = 0; i < 3; i++) {
            if (i != index) {
                rate[i] = rate[i] * (1.0 - r) / (1.0 - rate[index]);
            }
        rate[index] = r;
        }
    }

I think the simplest approach is to rescale the values.
The values other than the one you're setting currently sum to 1.0 - rate[index]. You want them to sum to 1.0 - r. You can therefore scale each of them by (1.0 - new_value) / (1.0 - old_value) to preserve the sum.
public void setRate (int index, double r) {
    for (int i = 0; i < 3; i++) {
        if (i != index) {
            rate[i] = rate[i] * (1.0 - r) / (1.0 - rate[index]);
        }
    }
    rate[index] = r;
}

This solution avoids:

Different code for positive and negative changes
Having to handle underflow (something + diff going below 0.0) and overflow (something + diff going above 1.0)
A value going from zero to non-zero, or vice versa. If the player set something at 0, then they probably want to keep it there.

Side note: a geometric interpretation is that your three values are coordinates in a cube. You constrain x + y + z = 1.0 so that puts you on an equilateral triangle embedded in the cube. Thinking about it this way helped me come up with the above solution.

Note that this solution can still fail, if 1.0 - rate[index] is 0.0. That will happen when 100% of the resource is assigned to one value, and you try to take away from it. I guess you'd have to handle this special case, probably by evenly distributing the remainder to the other values. If you treat 0 values as epsilon instead of 0.0 then it will work out, I think.

Would something like this work to write before the for loop?
Look at the Edit.

That looks like it should work. A unit test for this function should include cases where rates before and after are 0.0 and 1.0.

You could divide diff by two and then subtract it or add it accordingly to the other two.
double diff = r - rate[index];
double change = diff/2 * -1; //we need to reverse the operation

for(int i = 0 ; i < 3; i++)
{
    if(index != i) rate[i] += change;
}

Still you should be careful for number precision errors.
For that you could use an int[] where all values sum up to 100.

You'll also need to handle upper and lower bounds. For example, if you start with {0.4, 0.6, 0.0} and want to increase the first to 0.5, then =change= will be -0.05. You'll end up with {0.5, 0.55, -0.05}.

One way to do this is to add to the indexes' value by its self multiplied by diff. rate[i] = rate[i] + rate[i]*diff where i is the other to values other than index
    double d = 1 - rate[index]
    double diff = rate[index] - r;
    rate[index] = r;
    index = (index + 1) % 3;           // increment and wrap around index
    rate[index] += diff*rate[index]/d;
    index = (index + 1) % 3;           // increment and wrap around index
    rate[index] += diff*rate[index]/d;

Hope that helps.

Say I want to raise gold income from 0% to 50%
But with your solution I would add 25% to both science and luxury goods and not raise the gold income (or decrease it). Also this only works when the index is 0. If I want to change the luxury the index is 2. Then I would add 1, have 3 and get an Exception.

You are correct diff should be defined as follows diff = rate[index] - r. Also I didn't include it but right after diff is define the new rate from which ever index should be set with the following statement rate[index] = r. The index should never equal 3 because any sum of index + 1 greater than 3 should result in a integer between 0 to 2 do to the modulus operator, %. I also forgot some semicolons. I just edited the code and it should would now when put inside your method.


text:
Camera controller in a 2d platformer
I'm basically bumming around using Unity's 2D creation tools, and I've managed to create a little platformer physics demo. There's a lot of work to be done, but I've got basic movement down, some sounds working, basic jumping physics, and whatnot.
One of the things that's on my list of things to tackle is the camera system.
I experimented with locking the camera to the player position; it's simple, but works. However, I'd like to attempt to develop a more complex camera system that would follow level constraints, but still allow for free vertical and horizontal movement. Currently, I have the camera only matching the player's movement on the X axis, which means that jumping doesn't affect the camera. However, the camera won't follow if you climb a tall ladder.
(Think of the viewport from the Megaman X SNES games; there are many vertical and horizontal segments, but the camera is smart enough to let the player character (X) jump or cling to walls at the edge of the viewport without moving, yet move when the player is in an open area. This is the type of camera I'd like to achieve.)
I'd like to know how this problem is commonly approached. I thought about creating a spline, perhaps, and having the camera follow the spline path while still tracking the player. This spline would be specific to each created level. However, I'm not sure if this is the correct solution (and I'm not sure how it would work in open areas). The other thing that might be possible could be to set bounds for the actual camera limits, and not allow the camera to move outside of that, but I feel as though that might be a brittle solution in tighter areas.
Could someone with experience point me to any resources, or suggest advice to go in the right direction? Thanks!
Edit: To make this more clear, I've included a link to Flame Mammoth's stage in Megaman X. Notice how, in the first part of the stage, X can dash along the ground, while the camera tracks his x-position; later, it tracks his y-position when he falls down a shaft. Further on, there's a large room where the camera tracks X's movement without any boundaries until he gets close to the top of the screen; the camera doesn't pan past those boundaries.
Of note, I found a solution here that helps with jumping; I believe that MMX uses a variant of this. However, notice that in the custom game at the bottom, the camera is allowed to pan "out of bounds" as it's not limited by the level.

Just go really simple. Add a flag to the player that tells the camera when they're jumping. If they're jumping, don't follow them up.
The other situation you need to handle is when the player jumps up or down to different levels. In this case it would be pretty simple to start tracking again when the player touches down, or if the player goes below the starting position of the jump, the camera will start following again.
For keeping the camera in bounds, you have a few different options.

Create a bounds object that the camera tests before moving to ensure that it doesn't move outside. This is a quick and easy thing to implement, but only deals with the camera position, and not the view frustum. This means you might have to do a lot of tweaking to the bounds to make sure it doesn't see anything outside the bounds, and gets tricky-er if you have any kind of zoom. To implement this, you can create a number of objects with bounds, add them all to the same layer, something like CameraBounds, then, when testing a new position before moving there, do something like a physics overlap sphere (passing in the CameraBounds layer mask) to make sure the new position is inside one of your bounds objects.
Unity has a method called OnBecameVisible. You can place objects near the outside edges of your level. When these become visible to the camera, they tell the camera to stop tracking in that direction. This'll take some tweaking to get a smooth feel, but would ensure that no matter the zoom or camera position, you wouldn't see anything outside the level.
Finally, you have a predefined path. This is a path that the camera will "gravitate towards". The camera will also follow the character, but the farther it gets from the predefined path, the less effect the character's position has on the camera position. This will likely give you the best results, but is also probably the most work.

Sorry, I might not have been clear with my question. This addresses the jumping aspect (especially the different levels; thinking about it, I think that's how it's done in MMX, so thank you for that!), but I'm more concerned about the camera clipping incorrectly. Somehow, camera bounds are set so that you can't see outside the level in a 2D platformer. This behavior overrides the "keep the player in the middle of the screen" rule. Does that make sense?

Yep, I'll update.

I added a bit to my question to hopefully make it more clear. I realize that I'm not really explaining it very well - it'd be easier if I had a whiteboard or something. :P

Whoa, this is awesome! Thanks, dude. The third option is what I was thinking with the spline idea - I also thought that it might be possible to use multiple cameras and switch between them in different areas. However, I'll definitely try the first option and see what mileage I can get out of it.


text:
C++ timer function acts as if time limit is instantly reached if it is less than 1 second
I'm trying to make a Snake clone with C++ and OpenGL/GLUT, but I've been having trouble with programming the timed input. I made a timer class, as you'll see below, to be used for the short time intervals allowed for input and movement. It's function checkTime() is called to start the timer. Then on following calls, it checks if the time limit (represented by the int variable limit) has been reached.
To test it, I set up a simple, looping console program, that displays keyboard input. When working properly, it displays what key is being held precisely at the point when the timer finds the time limit has been reached (it returns "true"). Given a limit of 1 second, it will only display current input every second. If it is given a value below 1 however, like 0.333, it will act as if the time limit has instantly been reached, and will display input instantly whenever a key is pressed. How can I get it to only display the input every 0.333 seconds?
Also - I realize my method of doing things here may not be the best, given the tools I'm using. However, I'm curious why this won't work properly.
#include <iostream>
#include "timer.h"
// Include all files necessary for OpenGL/GLUT here...

using namespace std;

Timer timer;

void update(int value)
{
    if (timer.checkTime())
    {
        if (GetAsyncKeyState(VK_LEFT))
            cout << "You pressed LEFT!" << endl;
        else if (GetAsyncKeyState(VK_RIGHT))
            cout << "You pressed RIGHT!" << endl;
        else if (GetAsyncKeyState(VK_UP))
            cout << "You pressed UP!" << endl;
        else if (GetAsyncKeyState(VK_DOWN))
            cout << "You pressed DOWN!" << endl;
    }

    glutTimerFunc(1000/60, update, 0);
    glutPostRedisplay();
}

timer.h
#pragma once

class Timer
{
public:
    Timer();
    bool            checkTime(int limit = 0.333);
private:
    unsigned long   getElapsed();
    bool            running;
    unsigned long   elapsed;
    unsigned long   start;
};

timer.cpp
#include "timer.h"
#include <ctime>

Timer::Timer()
{
    running = false;
    elapsed = 0.0;
    start = 0.0;
}

bool Timer::checkTime(int limit)
{
    (unsigned long) limit;

    elapsed = getElapsed();

    if (elapsed < limit)
    {
        return false;
    }
    else if (elapsed >= limit)
    {
        running = false;
        return true;
    }
}

unsigned long Timer::getElapsed()
{
    if (! running)
    {
        start = (unsigned long) clock();
        running = true;
        return 0.0;
    }
    else
    {
        return ((unsigned long) clock() - start) / CLOCKS_PER_SEC;
    }
}

int limit = 0.333. ints are integers. You probably want float.

A great reason to work with warnings turned up high, and to actually read the compiler output, both of which should have given a warning about truncating a float or some such.

Thanks for your input! I had meant to make it a float, and I will definitely be more careful to check for compiler warnings.

int limit = 0.333;

is the same as
int limit = 0;

because int has no decimal places. So you ether work in fixed point where the number is divided by a fixed amount, or floating point.
so for example if doing fixed point hundredths, you would use,
const int FIXED = 100;

unsigned long Timer::getElapsed()
{
    if (! running)
    {
        start = (unsigned long) clock();
        running = true;
        return 0;
     }
     else
     {
         return ((unsigned long) clock() - start) / (CLOCKS_PER_SEC/FIXED);
     }
}

and fixed could be
int limit = (unsigned long)(0.333 * FIXED);

I wouldn't define it like the above, but leaving it in form you would reconise.

Embarassing! I can't believe I didn't notice it was an integer. Thanks for a prompt, informative answer! Didn't know it would literally change to 0.


text:
Trying to understand the XNA fixed time step game loop logic
I came across the blog post Understanding GameTime, and after lots of reading on fixed time steps in game loops this is the approach I would like to take. In summary, this is the logic from the post:

Set the desired time spent in Update + Draw as 1/60 of a second (fixed 60 fps).
If time elapsed since last Update + Draw is exactly 1/60 of a second:

Call Update
Call Draw
Tick (Game loops.)

If time elapsed since last Update + Draw takes less than 1/60 of a second:

Call Update
Call Draw
Look at the Clock (Time left over? Wait.)
Tick (Game loops.)

If time elapsed since last Update + Draw takes more than 1/60 of a second?

Call Update (Until we catch up.)
Call Draw
Tick (Game loops.)

I guess the two parts I'm having trouble understanding is in #3, how would the waiting be accomplished since thread sleeps are often not accurate enough, and what does it mean in #4 to call update until we catch up? Catch up to what since the time elapsed is already greater than our target 60 fps?

I guess the two parts I'm having trouble understanding is in #3, how
  would the waiting be accomplished since thread sleeps are often not
  accurate enough?

Can't answer this for sure as I haven't seen the XNA source code.
MonoGame uses thread.sleep
// NOTE: While sleep can be inaccurate in general it is
// accurate enough for frame limiting purposes if some
// fluctuation is an acceptable result

From my understanding System.Diagnostics.Stopwatch is likely the highest resolution timekeeping utility you have access to as a part of .net.

What does it mean in #4 to call update until we catch up? Catch up to
  what since the time elapsed is already greater than our target 60 fps?

Lets say each |----| is a 60hz tick. * is when update is actually called. For some reason a first update took way to long (perhaps it loaded a bunch of new stuff). Basically all 4 is saying is its going to call update as fast as possible with no waiting until the number of times update has been called has caught up to the number of times it ought to have been called optimally .
*       *    *    *    *   *   *   *<---- Caught up here
|----|----|----|----|----|----|----|
0    1    2    3    4    5    6    7

"...until the number of times update has been called has caught up to the number of times it ought to have been called optimally" Does that mean keeping track of how many ticks have occurred for comparison against how many ticks should have occurred? If not, what would be the appropriate comparison? On the XNA blog post I mentioned he did say at some point they give up if it gets too far behind, which confused me further.

"Does that mean keeping track of how many ticks have occurred for comparison against how many ticks should have occurred?" Yes. "On the XNA blog post I mentioned he did say at some point they give up if it gets too far behind, which confused me further." Basically if takes too long to catch up it is best to revert back to running at regular intervals. If you can't even do that it degrades into just running as quickly as possible. I know my language is vague but without having seen exactly how XNA implements the looping broad strokes is the best I can do.

That's okay, even with a little vagueness it does clarify things for me so I don't head down the wrong path. Thanks.


text:
Binary Serialization of C# for GameObject in Unity?
I'm trying to serialize a GameObject (with children and textures) using the binary serialization for C#.
It works with many data types but not with GameObject. In the docs it says should be serializable (http://docs.unity3d.com/ScriptReference/SerializeField.html):

Serializable types are:
   - All classes inheriting from UnityEngine.Object, for example GameObject ....

I've read suggestions of using the asset of UnitySerialization, but that is overkill for me, I just need to store a GameObject on my scene (that will be generated by many users) and load them all in another scene.
This is the code (I'm following this tutorial: http://www.youtube.com/watch?v=J6FfcJpbPXE&feature=player_embedded)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class GameControl : MonoBehaviour {

    public static GameControl control;

    public GameObject drawing;
    public string drawName;

    void Awake () {
        if (control == null)
        {
            DontDestroyOnLoad(gameObject);
            control = this;
        }
        else if (control != this)
        {
            Destroy(gameObject);
        }
    }

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    public void Save ()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/drawing.drawli");

        UserDraw data = new UserDraw();
        data.drawing = drawing;

        bf.Serialize(file, data);
        file.Close();
    }

    public void Load()
    {
        if (File.Exists(Application.persistentDataPath + "/drawing.draw"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/drawing.draw", FileMode.Open);
            UserDraw data = (UserDraw)bf.Deserialize(file);
            file.Close();

            drawing = data.drawing;
        }
    }

}

[System.Serializable]
class UserDraw
{
    public GameObject drawing;
}

Check the Save/Load functions. I'm just trying to store the "drawing" (GamObject), save it and load it. That's all! Is very simple. With other data types it works. But not with GameObject.
This is the (execution) error:
SerializationException: Type UnityEngine.GameObject is not marked as Serializable.

You might want to check out this video where Tom shows how he converts everything into a byte array and then serializes all of it.

SerializationException: Type UnityEngine.GameObject is not marked as
  Serializable.

That means UnityEngine.GameObject is not marked with the Serializable attribute, which is a requirement (just because Unity says a type is serializable doesn't mean it's serializable with all serialization engines; in this case, it probably means that the type is serializable with Unity's engine, not the one that is part of the .NET BCL).
You can either use Unity's serialization mechanism, or you can try your hand at implementing an ISerializableSurrogate object for the Unity game object (this is likely to be tricky, and more effort than just using Unity's serialization).


text:
Save Texture2D to file in Monogame
I'm working on a tilesheet builder tool for my game to speed up tile creation, and I need to save a generated texture2D as a png. I've tried using the .SaveAsPng function but it isn't implemented in Monogame.
Is there any way around this in monogame?
EDIT:
I've tried this:
private void SaveTextureData(RenderTarget2D texture, string filename)
    {
        byte[] imageData = new byte[4 * texture.Width * texture.Height];
        texture.GetData<byte>(imageData);

        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        System.Drawing.Imaging.BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
        IntPtr pnative = bmData.Scan0;
        System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 * texture.Width * texture.Height);
        bitmap.UnlockBits(bmData);
        bitmap.Save(filename);
    }

but it's giving a weird output, and I don't know why:
https://i.stack.imgur.com/dGTxr.png
Thanks for any help!

Did you try debugging the issue? Verify your data is accurate, and that your methodology even works with known good data. Worst case scenario you have to write out the data manually. Bitmaps are a simple file format, here is the specification. https://www.daubnet.com/en/file-format-bmp

Your code seems like it would work to me, but there are two things you would need to verify:

Is the render target's format RGBA? Or is it just RGB?
Are you trying to save as a PNG or a BMP? Bitmap.Save() defaults to a BMP image. To save as a PNG, you need to use this overload.

Also, if MonoGame is using the OpenGL renderer, I remember with OpenTK the Bitmap internal format was actually BGRA or something similar (even when specifying PixelFormat.Format32bppArgb), so the byte order may be messed up.

Thanks for the advice, turns out I just messed up the array sorting code, silly error that I didn't catch!

 private void SaveTextureData(RenderTarget2D texture, string filename)
        {
            byte[] imageData = new byte[4 * texture.Width * texture.Height];
            texture.GetData<byte>(imageData);

            //Add this
            for (int i = 0; i < imageData.Length; i+= 4)
            {
                byte b = imageData[i];
                byte g = imageData[i+1];
                byte r = imageData[i+2];

                imageData[i] = r;
                imageData[i + 2] = b;
            }

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            System.Drawing.Imaging.BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
            IntPtr pnative = bmData.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 * texture.Width * texture.Height);
            bitmap.UnlockBits(bmData);
            bitmap.Save(filename);
            bitmap.Dispose();
        }

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Resources for designing (not programming) 2D platformer mechanics
I've been making a 2D platformer in Unity and it's been going great. I have the fundamentals down (and as an experienced programmer, I know how to get the results I want; this is not a programming question.)
I've been floundering, though, because I realize that I lack vision in terms of a game direction. I originally wanted to make a Metroidvania-style game, but decided to scale back as I thought that would be too ambitious (and take too long) for my first game. As such, I've decided to create a platformer/run-and-gun type game.
I've played enough platformers to know and intrinsically understand basic mechanics, but I also realize that the best games have a core mechanic that defines the game. Megaman's core mechanic, for instance, is obtaining and using boss weapons and abilities; boss battles and levels are built around this. Metal Slug revolves around weapon pickups and its tank gameplay.
I guess I'm at the point where I have a code demo....but it's not a game; it has no soul. I've basically just proven to myself that I can write a platformer game in Unity.
I want to know of any good resources on aspects of video game mechanic design not centered around programming - book recommendations would be amazing, but online resources or other types of resources would be great as well. (Worth noting that I'm not looking for guides on designing levels, but lower-level mechanics, like jump height, hp limits, core mechanics to define a game, etc.)

There's a very long blog post that might provide some guidance on Metroidvania type design here: http://subtractivedesign.blogspot.com/2013/01/guide-to-making-metroidvania-style.html

Unfortunately, list generation type questions are too open ended for the format of the site.

One of the best resources for mechanical design is pen and paper. Everything that happens on a computer happens one step at a time, which means you can prototype just about any part of your game using paper.
As for what's best (you mentioned jump height), it's really a question of what's best for your game, so the best way to figure it out is to play with it. That's where paper helps, as you can reiterate quickly and not worry about implementation. Aside from paper, you could set mechanic-specific variables (such as jump height) as public, as long as they are implemented this allows quick iteration by changing the variable in Unity's inspector.
When you're thinking about a hook mechanic for your game, remember it can be pretty much anything, as long as you actually include it in the game! Think of Mario - personally I'd say the main mechanic there is jumping:

Enemies are defeated by jumping
Levels are traversed by jumping
Puzzles are solved by jumping
Power-ups affect jumping (even the fireball cuts down enemies so you can focus on jumping)
... Jumping

You could however design pretty much any type of game around any mechanic (that doesn't mean it's going to be a killer game). How about a platformer based around acrobatics? Strip out the combat and that's pretty much Prince of Persia. Or a platformer based around environmental manipulation (Gravity Guy is a great example of that). Say you wanted to do Gravity Guy, you could still keep run-'n'-gun, just like Mario has Goombas but the main thing you're doing to get around a level would be flipping.
Finally, one of the best books I could ever recommend on game design is David Perry on Game Design as I find it's pretty much just a massive toolbox.


text:
How to prevent a circular dependency between an entity and its state?
I've read this question, and I think it has some good answers and discussion, but it appears to focus primarily on rendering.
I have a different problem in the management of a game entity's state. What I end up with is this:
Game -> Player -> FSM -> State -> Player
Upon entry into a state a pointer to Player must be passed through, but no matter what I do in C++ it has trouble resolving this relationship hierarchy.
A good deal of how I'm designing my FSM is like this article. However, that is a psuedo implementation, and does not use headers. Without moving completely over to behavior trees is there another design pattern that will eliminate this circular dependency?

I don't follow what the problem is. There is no reason conceptually that what you are saying you're doing wouldn't work. Post a (simplified) snippet of problematic code and the related errors.

I reverted some of my changes so the error no longer appears, but I can re-implement and compile again so that I can post the code here. I've been reading up on forward declarations, but they seem to get mixed reactions, and some developers argue if I have a circular dependency at all then it must have been designed wrong.

"some developers" aren't writing your game. Don't get caught up in academic arguments of design purity from people who aren't invested in producing the best version of your end product. There's generalized good design advice which you should follow when you can but don't get hung up on it. :)

Thank you for that encouragement. I've been in the Java world for a long time, and so getting deeper into C++ is a mix of excitement and trepidation.

you can use a forward declaration of the class that are in circular dependency.
Here an explanation
class firstClass; //Here the forward declaration
class secondClass
{
  public:
  private:
};

Then in the cpp of the second class you can include the firstClass header file.

Using forward declaration whenever possible in header files is good practice, as it will minimize your compile times. The main restriction is you won't have access to any functionality from the class, so you'll have to use pointers and you won't be able to call any functions (in the header file).

So it turns out after a lot of research and a very brief sandbox attempt I reproduced the error. It is ultimately a problem with forward declaration vs. using includes everywhere.


text:
Draw lines from the center of the screen at specific angles
I want to draw multiple primitive lines which start at the center of the screen and end at the edges of the screen, traveling at specific angles:

How can I set the angle for each line?
Here is my code where I draw only one line from the middle of the screen to the top of the screen.
LineVertices = new VertexPositionColor[2];
LineVertices[0].Position = new Vector3(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2, 0);
LineVertices[0].Color = Color.Red;
LineVertices[1].Position = new Vector3(graphics.GraphicsDevice.Viewport.Width / 2, 0, 0);
LineVertices[1].Color = Color.Red;
.
.
.
//Draw call
graphics.GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, Line2Vertices, 0, 1);

This is essentially simple trigonometry. Assuming the center of the screen is your origin (i.e. (0, 0)), then it's pretty straightforward:
x = length * sin(angle);
y = length * cos(angle);

Just insert the proper numbers and you end up with your vertex coordinates.

Thank you very much. That helped a lot. I'm really bad at trigonometry. I need to get a trigonometry book. Thanks again ^_^


text:
Why are my sprite outlines partially rendering in the wrong place?
I've been trying to draw an outline around a sprite using the code from this answer.
Details
My sprite is called Ship2Sprite.
This is how I create the rectangle:
 rectangle = New Rectangle(backgroundPos.X + NPCAI.enemyPosistion.X,
                           backgroundPos.Y + NPCAI.enemyPosistion.Y,
                           Ship2Sprite.Width, Ship2Sprite.Height)

This is how it looks without any rectangle drawn:

If I use this line of code
hudSpriteBatch.Draw(t, rectangle, New Rectangle(0, 0, 0, 0), Color.Red,
                    NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)

the following is the result in game

hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, 2, rectangle.Height), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Right, rectangle.Top, 2, rectangle.Width), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)

However, when trying to use the code from the linked answer, this is the result:

The first and third lines produce the correct lines, however the other 2 are in the correct orientation but not the correct position
Am I missing something somewhere?
EDIT
Based on Blau's answer, I have updated my code to this:
 Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice)

    Dim spriteBatch1 As New SpriteBatch(graphics)
    Dim rectangle As New Rectangle(Game.backgroundPos.X + pos.X, Game.backgroundPos.Y + pos.Y, sprite.Width, sprite.Height)
    Dim w = rectangle.Width
    Dim h = rectangle.Height
    Dim x = rectangle.X + w / 2
    Dim y = rectangle.Y + h / 2
    Dim transform As Matrix = Matrix.CreateRotationZ(NPCAI.enemyAngle) * Matrix.CreateTranslation(x, y, 0)

    spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform)
    x = -w / 2
    y = -h / 2

    spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y + h - 2, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x + w - 2, y, 2, h), Nothing, Color.White)
    spriteBatch1.End()

End Sub

However the rectangle is rendering in the wrong position, which is slightly ahead of the sprite. Like this
EDIT 2, with the following code
 Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice, ByVal angle As Single)

    Dim spriteBatch1 = New SpriteBatch(graphics)
    Dim rectangle As New Rectangle(Game.backgroundPos.X + pos.X, Game.backgroundPos.Y + pos.Y, sprite.Width, sprite.Height)
    Dim w = rectangle.Width
    Dim h = rectangle.Height
    Dim x = rectangle.X + w / 128
    Dim y = rectangle.Y + h / 128

    Dim transform As Matrix = Matrix.CreateRotationZ(angle) * Matrix.CreateTranslation(x, y, 0)

    spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform)
    x = -w / 128
    y = -h / 128
    ' spriteBatch1.Draw(t, rectangle, Color.Red)
    spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y + h - 2, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x + w - 2, y, 2, h), Nothing, Color.White)
    spriteBatch1.End()

End Sub

I mischievously pinged the author of that code you linked, since that's where the problem seems to lie. :3

Pixel color addresing is bad, it will work on a square but not on a rectangle.
Change this:
 colors[ x * texture.Width + y ] = borderColor;
 colors[ x * texture.Height + y ] = Color.Transparent;

To this:
 colors[ x + texture.Width * y ] = borderColor;
 colors[ x + texture.Width * y ] = Color.Transparent;

EDIT: If you are using the other method, your problem is the rotation
You have to use a transform matrix and generate the rectangle based in (0,0) as origin.
var w = rectangle.Width;
var h = rectangle.Height;
var x = rectangle.X + w/2;
var y = rectangle.Y + h/2;
Matrix transform = Matrix.CreateRotationZ(NPCAI.enemyAngle) * Matrix.CreateTranslation(x,y,0);

husSpriteBatch.Begin(,.,..., transform);
x = -w/2;
y = -h/2;
hudSpriteBatch.Draw(t, new Rectangle(x, y, w, 2), null, Color.White);
hudSpriteBatch.Draw(t, new Rectangle(x, y+h-2, w, 2), null, Color.White);
hudSpriteBatch.Draw(t, new Rectangle(x, y, 2, h), null, Color.White);
hudSpriteBatch.Draw(t, new Rectangle(x+w-2, y, 2, h), null, Color.White);

husSpriteBatch.end();

Sorry I have updated the link to the correct answer because I got better results with the answer, I tried this way and cannot call the method from initialization because the texture isn't loaded yet, and when I call it into draw I get an invalid operation exception.

if your intialization method has this code
square = new Texture2D( GraphicsDevice, 100, 100 );
square.CreateBorder( 5, Color.Red );
It has to run without problem

I tried the updated code in your answer, and it produces this, the rotation and rendering is fine, however it seems to be offset infront of my sprite for some reason, do you have any idea why this might be happening? I'm sure the position I'm passing to it is correct. Will update OP with details, Thanks

I though you was rotating your ship about its center, better than divide by 128, change w/128 and h/128 by 0


text:
How to specify colour in a single 32 bit value
I'm writing my first game using OpenGL 2 ES (for Android), and I've currently got a particle engine and some player sprites running successfully.  I'm using 4 floats for the colour of each particle which seems like total overkill.  It makes sense that I should be able to use a single 32 bit int (or perhaps a single float) to hold the colours (perhaps in RGBA format) which would presumably save a lot of unnecessary loading/copying/processing,  but I'm struggling to understand how I could do this.
I guess that I would need to change the shaders to take the relevant format, and also i'd need to change the way I load the color shader attribute.  My fragment shader has:
varying vec4 v_Color;
gl_FragColor = v_Color * texture2D(u_TextureUnit, gl_PointCoord);

and the attribute (passed into the fragment shader from the vertex shader) is set up with:
glVertexAttribPointer(aColourLocation, COLOUR_COMPONENT_COUNT, GL_FLOAT, false, BYTES_PER_VERTEX, floatBuffer);

I've searched the documentation for what I should change vec4 and GL_FLOAT to, and what/how I'd multiply the colour with the texture, and have tried a few things but with no success.

You are looking in the wrong place you should set the draw buffer to a 8 bit format, all the rest happens automatically

@ratchetfreak Not sure what i'd do to the shader/attrib setup. What types do I use?  How do I do the colour multiply?

this might help http://www.opengl.org/wiki/Image_Format

@Aralox Thanks, that seems relevant. Seems that what I want would be GL_RGBA8UI. Sadly, it doesn't look like this is available on OpenGL ES 2.0 for Android: https://developer.android.com/reference/android/opengl/GLES20.html#GL_RGB Or am I misreading that?  Should I be worried about trying to use 4 bytes instead of 16 to specify the colour of each particle?

Fragment shaders operate with floats.  This is an abstraction over the actual underlying hardware format (GLSL is a high-level language after all), so you shouldn't expect that to indicate that you've actually got a floating-point framebuffer.  You'll always use vec4 in your fragment shader irrespective of if you have a 16-bit, 32-bit, 64-bit or 128-bit framebuffer, and there's no memory overhead for doing so.
There's no need to change your fragment shader; don't fall into the trap of thinking that the high-level GLSL you write is any way representative of the low-level hardware instructions that actually run.
For sending colours as a 4-byte format you adjust your glVertexAttribPointer call so that it's using GL_UNSIGNED_BYTE for the type parameter and GL_TRUE for the normalized parameter.  Then also adjust your source data, and you can start sending colours as 4 bytes with a 0-255 range, in RGBA order.  The hardware will automatically convert them to floats in a 0-1 range and your fragment shader, once again, remains exactly the same as before.  Don't sweat the details of whether or not this is a slow operation: it isn't.
Beware of thinking you're going to be even more efficient if you decide to only send 3-bytes sometimes: hardware prefers to operate on 32-bit boundaries and while you will save a small amount of memory you risk running substantially slower as a result.

I guess I have to have an array of ints with which to feed the colour attribute, given that were I to continue to use a float there'd be some corruption to my RGBA int.  (When changing my code to take your answer into account I discovered that I had to use ABGR format within my ints (the alpha is in the 8 most significant bits).   I guess this is an endian thing - i'm using the native order in my IntBuffer)


text:
Collision detection across multiple components
I have been reading this article: http://gameprogrammingpatterns.com/component.html which describes how a game object should be constructed out of components. It also encourages the decoupling of components, which brings up a problem with input, collision detection, and things that cause events to be triggered.
If I have a game object, which is a player and this player has 3 components; PlayerSoundManager, PlayerCollisionDetection, and PlayerStateManager, how would I go about making sure they have no references to each other? If PlayerCollisionDetection detects that a player should die, messages should be sent to the other two components telling the player to play a death sound, and change it's state.
Would it be wrong to put collision detection methods throughout all components and perform each reaction separately?

No, but it will just be bad manners to write the same thing in every scripts and it can be a pain to debug if you have lots of function of collision detection in a lot of other scripts.
You can use the method SendMessage() to communicate between scripts (or inside a script).
You can read its documentation here
e.g
if(player.health == 0){
  gameObject.SendMessage(playerStateManager.changeState, 'dead');
  //where playerStateManager is a reference to your class PlayerStateManager
  gameObject.SendMessage(playerSoundManager.play, 'deathSound');
  //where playerSoundManageris a reference to your class PlayerSoundManager
}


text:
How to deal with tags in a component
I have a component called "ReflectOffCollision". This component should obviously not need to be aware of specific details about the game such as tags. The problem is, I want to apply this script to an object that reflects off of only some collisions.
I could check the tag of the collision, but this will destroy the generality of the component. It will only work on collisions with this tag. I could have the script take a white list or black list of tags, but this is awkward to do.
My other option is to inherit from the component and make a more specific version. This seems like overkill, though.
How should I deal with tags in components? I see this problem anywhere that there are collisions. Am I using tags incorrectly, or misunderstanding them?

Does your object (which has this script) collide "normally" with Objects which would not trigger this Script?

Yeah. In this particular case, I want this object to reflect off of the level mesh, but behave differently when colliding with a player object.

There are a few ways to achieve this. First, you can use layers and modify the collision matrix so that it won't interact with non-collidable objects. Second, objects you want to collide can contain a common component to mark them as collidable.
Let's say it's Reflectable. At run-time, you can determine whether the object is collidable or not with this:
if(collision.gameObject.GetComponent<Reflectable>()!=null)
    collide();

Wouldn't that just be an empty component that now has to be added to everything that's reflectable just for the sake of doing this?

Yes, it would be an empty component. However, you can define a Movable base class and implement isReflectable() method and derive your controller classes from it also.


text:
Calculate needed speed and object's position in Unity3d
So I'm trying to calculate an object's future position so my enemy can land to it safely. Idea is that using the future position I can calculate the angle and convert it to a direction vector and also using distance I can calculate the speed necessary to reach its target. I'm still kind of stuck with this idea.
Here is code which I'm using at the moment.
// Find the close platform to land
Transform _tmp = GetClosestPlatform(SpawnerNew.Platforms);
// Hard coded time, should be time which enemy should take to reach position
float _constNeededTime = 3f;
// As my game's speed always increasing every frame so I need to calculate it also how it's in future (GameManager.Instance.OverAllSpeedModifier is called 10x times / sec)
float _anticipatedLevelSpeed = GameManager.Instance.CurrentLevelSpeed + (GameManager.Instance.OverAllSpeedModifier * _constNeededTime * 10);
// trying to calculate the future postion of the platform
Vector3 _anticipatedLoc = _tmp.transform.position - new Vector3((_platformSpeed * _anticipatedLevelSpeed) + _constNeededTime, 0f, 0f);
// Calculate angle
float _angle = Mathf.Atan2(transform.position.y - _anticipatedLoc.y, transform.position.x - _anticipatedLoc.x) * 180 / Mathf.PI;
// Convert angle to vector direction
_nearestPlatformDir = new Vector3(Mathf.Cos(_angle * Mathf.PI / 180f), Mathf.Sin(_angle * Mathf.PI / 180f), 0);
// Trying to calculate speed needed to reach platform
_neededSpeed = Vector3.Distance(_anticipatedLoc, transform.position) / _constNeededTime;

Forget trigonometry. Use vector math. Think of it as solving an equation: you want the position of the platform and the position of the enemy to be the same at some point in the future. So you write the equations of motion for both, and solve for the velocity of the enemy:
platform_x = platform_x0 + vel_platform0 * t + accel_platform * t^2 / 2
enemy_x = enemy_x0 + vel_enemyx * t
enemy_y = enemy_y0 + vel_enemyy * t

Note that I've written those assuming that the platforms accelerate over time, as you describe in your post. The enemy, by contrast, will move at constant velocity towards the platform.
Now in order to hit the platform, we need the values to be the same for some time T:
platform_x(T) = enemy_x(T) =>
platform_x0 + vel_platform0 * T + accel_platform * T^2 / 2 = enemy_x0 + vel_enemyx * T

platform_y(T) = 0 = enemy_y(T) =>
0 = enemy_y0 + vel_enemyy * T

Notice that we have three variables to solve for (T, vel_enemyx, vel_enemyy) and only two equations. This makes sense, as we can have the enemy move really quickly towards the platform, and hit it earlier, or move more slowly and hit it a bit later.
In your example, you fixed the time T to 3 seconds, so substituting that you can then easily solve vel_enemyx and vel_enemyy.
EDIT:
Using your variables, code would be something like:
float vel_enemyx = 1/_constNeededTime * (_tmp.transform.position.x + GameManager.Instance.CurrentLevelSpeed * _constNeededTime + GameManager.Instance.OverAllSpeedModifier * 10 * _constNeededTime * _constNeededTime / 2 - transform.position.x);
float vel_enemyy = -transform.position.y / _constNeededTime;

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/