text:
Pygame time.get_fps() value
I was looking at the pygame.time.Clock.get_fps() method and after puting it inside of the while loop printing and checking it some times, i see that i starts to give its value after five frames (and not 10 as said in the documentation). I did put this inside the while loop (clock is the object of the pygame.time.Clock() class created inside my class):
 print "clock.tick:", self.clock.tick(self.fps)
 print "clock.get_fps", self.clock.get_fps()

and the result by having the fps=60 was:
clock.tick: 48
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 51.8134689331
clock.tick: 16
clock.get_fps 51.8134689331
clock.tick: 16
clock.get_fps 51.8134689331
clock.tick: 16
clock.get_fps 51.8134689331
clock.tick: 16
clock.get_fps 51.8134689331

As one can see the first clock.get_fps comes out after the first 5 calls, but it supposedly should calculate the average of the last 10 calls to tick(). What am i missing here? Can anyone help explain this?

Looking at the implementation of clock.tick() and where in that module the FPS value is set (search for _clock->fps =), the documentation seems to be correct that it determines the FPS after 10 calls (which means at the 11th call) to tick(). Let's try with a more isolated example:
import pygame

clock = pygame.time.Clock()
fps = 60

for i in range(20):
    print '{}: tick={}, fps={}'.format(i+1, clock.tick(fps), clock.get_fps())

For me, this gives:
1: tick=17, fps=0.0
2: tick=17, fps=0.0
3: tick=18, fps=0.0
4: tick=16, fps=0.0
5: tick=19, fps=0.0
6: tick=17, fps=0.0
7: tick=18, fps=0.0
8: tick=17, fps=0.0
9: tick=17, fps=0.0
10: tick=17, fps=0.0
11: tick=19, fps=57.1428565979
12: tick=17, fps=57.1428565979
13: tick=18, fps=57.1428565979
14: tick=16, fps=57.1428565979
15: tick=19, fps=57.1428565979
16: tick=17, fps=57.1428565979
17: tick=18, fps=57.1428565979
18: tick=16, fps=57.1428565979
19: tick=18, fps=57.1428565979
20: tick=17, fps=57.1428565979

Given the fact that 5 is 10 divided by 2, I'd assume that you call clock.tick() (or clock.tick_busy_loop(), which both call clock_tick_base() internally) either directly or indirectly somewhere else in your game loop, so each iteration has two calls to clock.tick(), resulting in a FPS value already after 5 loop iterations.
This is using Python 2.7.11 on OS X and PyGame from Mercurial (pip install --user hg+http://bitbucket.org/pygame/pygame), which should be revision d61ea8eab at the time of writing, just in case you can't reproduce it on your installation.

What I figured out is you can do 1000 / clock.tick(60) and you would get an approcimation to the fps but it doesn't return 0 for the first 5 frames

try this: you type this in your code (anywhere in the code will work):
while True:
    print(clock.getfps())

and BOOM! it just prints the current fps in the console!

Is this valid pygame code?

Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.

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


text:
Using sourceRect or cropping out a Texture 2D to draw? MonoGame/XNA
I was wondering what is the best way to draw textures (for performance). Using the sourceRectange in the spriteBatch.Draw() call and just draw the whole spriteSheet, or crop out every texture on the spritesheet and store them in there own Texture2D object? Like this :
    public static Texture2D Crop(Texture2D spriteSheet, Rectangle source)
    {
        Texture2D croppedTexture2d = new Texture2D(spriteSheet.GraphicsDevice, source.Width, source.Height);
        Color[] imageData = new Color[spriteSheet.Width * spriteSheet.Height];
        Color[] croppedImageData = new Color[source.Width * source.Height];

        spriteSheet.GetData<Color> (imageData);

        int index = 0;

        for (int y = source.Y; y < source.Y + source.Height; y++)
        {
            for (int x = source.X; x < source.X + source.Width; x++)
            {
                croppedImageData [index] = imageData [y * spriteSheet.Width + x];
                index++;
            }
        }

        croppedTexture2d.SetData<Color> (croppedImageData);
        return croppedTexture2d;
    }

And just call that method in the LoadContent() method?

The sourceRect is much better for this.
Watch this if like a funny video explaining why:
https://www.codeandweb.com/what-is-a-sprite-sheet-performance
The more technical explanation:
I am using pseudo code - the exact number of commands required might vary - but you should see what I am talking about.
If you use isolated sprites the game engine has to perform the following actions on OpenGL (pseudo-code)
foreach sprite as s do
    gl->setTexture(s)
    gl->setSpriteCoordinates(s)
    gl->setDestinationCoordinates(s)
    gl->draw()
end

So you end up with approx. 4*number_of_sprites OpenGL calls. These commands are usually asynchronous - but depending on the exact calls you are using this might even trigger a synchronization between OpenGL and your code. That means: Your code waits until the draw operation is finished. Just wasting the CPU cycles during the refresh.
Using a sprite sheet and a sprite batch changes this completely:
foreach sprite as s do
    sourceCoordinates[] = s->sourceCoordinates()
    destinationCoordinates[] = s->destinationCoordinates()
end
gl->setTexture()
gl->setSpriteCoordinateList(sourceCorrdinates)
gl->setDestinationCoordinateList(desintationCoordinates)
gl->draw()

As you see only 4 OpenGL calls are required. It's simply setting the coordinate lists which have been pre-processed.
The drawing process runs now asynchronously without interruption and the CPU is free for other tasks.
The plain drawing process might take more or less the same time - but you've reduced the overhead for the communication - and the CPU is available.

I've never seen it explained like this. Very nice answer.

Using the sourcerect is better performance wise.
The GPU benefits from as little texture changes as possible. With a textureatlas one texture is sent to the GPU and all sprites can be batched without a texture change.
In reality sprites are actually quads with each vertex points to a coordinate in the texture based on the source rectangle. All vertices inside the same batch are then drawn as one drawcall.
This is the reason sprite atlasses are used.

source: Stack Exchange

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

sort: votes


text:
Detect Input.GetMouseButtonUp outside a GameObject in Unity?
How do I detect Input.GetMouseButtonUp outside a specific GameObject's area in Unity? Are there any Unity Assets for this?

Your question currently is not clear enough. Try editing it with more info. For instance, it's not clear what you mean by "outside a specific GameObject's area".

@MAnd question edited

You could do it using Vector3.Distance(...), checking the distance between the mouse click position and the object(s).
For simplicity though, I would suggest using colliders (sized according to your selection area) and casting rays from the mouse position.
void Update()
{
    if(Input.GetMouseButtonUp(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RayHit hit;
        if(Physics.Raycast(ray, out hit))
        {
            // do what you want
        }
    }
}

You can exclude certain object layers by passing an argument to the physics raycast call. Alternatively, just check that the collider you've hit belongs to a relevant object by checking it's tag, layer, name or one of its components.
Excluding certain layers using a layer mask would be my approach.
Edit:
Just to be clear, if you're checking that the click wasn't within one of the non-detection areas, you could use a layer mask to detect only these special colliders and then do:
if(!Physics.Raycast(ray, 1000, layerMask))
{
    // ok
}

Where 1000 is some max distance and the layerMask is used to exclude non-relevant layers.
http://docs.unity3d.com/ScriptReference/LayerMask.html

I personally wouldn't use layerMasks for a single object. hit.gameObject.tag or hit.gameObject.name will work as well to determin, if the object was clicked.

I see what you're saying. As you already suggested, the result will be the same. However, if you end up having a scene with overlapping objects or collision domains, a layer mask would offer superior flexibility for being able to filter out objects as well as a possible speed benefit as the ray can entirely ignore objects not on that layer (Unity specifics not withstanding)

Approach one
If this is a 2D game then I would suggest creating a quad and placing
  it below the rest of your objects. Then whenever GetMouseButtonUp is
  called fire a RayCast at the quad from the camera. If it hits the quad
  then you can progress the code. If it is stopped by another collider
  (i.e. collider defining do not detect here, then stop the code).

This approach I have decided would be worse to implement, I would go for the one below but have kept it in for the sake of completeness.
Approach two
Alternatively, for any areas where you do not want to have detection occurring assign them a layer i.e. NoMouseDetectionLayer then use the raycast and if it doesn't hit one perform the code.
public class GetInputs : Monobehaviour {
     int blockInputMask;
     // Range of the raycast (value not that important)
     public int camRayRange = 200f;

     void Start(){
         int blockInputMask = LayerMask.GetMask("NoMouseDetectionLayer");
     }

     void Update(){
         if(Input.GetMouseButtonUp()){
              Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);

              RaycastHit floorHit;

              if (!Physics.Raycast(camRay, out floorHit, camRayRange, blockInputMask)) {
                   // If it doesn't hit an object on the layer perform the code.
              }
              else{
                   // It hit the object so don't do anything.
              }
         }
    }
}

This has the benefit that it is easy to assign new areas, all you need to do is create a new object with a collider and set its layer as NoMouseDetectionLayer which is done in the top right of the inspector.

Where do I attach this script to?

Where you call Input.GetMouseButtonUp you add the code for the raycast and you change the layer of whatever object you want to stop input to "NoMouseDetectionlayer". Let me edit it so it is a bit clearer

Added some more code to make it clear how you would add the code to a script. Also noticed that this is pretty much the same answer as the one provided by Jack

I'm having difficulties with implementing your script. Can you please upload an example project?

I can do so later but cannot at the moment. The earliest I can promise is this evening but I might not get it done until tomorrow.

Hello. You don't have to upload an example project! I fixed the problem.

Oh really? Glad it worked out. What was the problem if you don't mind me asking?

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


text:
Stop Unity from smoothening out images
In Unity, low-resolution images are "smoothened out". Is there a way to keep them pixelated?
For your information, the images that I'll be using are in PNG format.

This effect is controlled by the Filter mode of the Image. You can change it in the Import settings.
To get a pixelated look, choose the option "Point (no filter)"

It so unusual but you may give a try to Max Size property of import settings.

Select your picture (from Project explorer, not from Hierarchy).
Set Max Size in inspector to lowest as much as you can.

Your answer led me to @user000user's answer which is the correct one. Props to you for your early reply: if I had more reputation points, I would upvote your answer.

If someone reads this, I suggest upvoting this answer.


text:
Player moving back and forth when moving with camera LIBGDX
I have a problem. When in libGDX my player moves across the screen and the camera is moving after him the player jumps back and forth a bit. Player still moves forward but it looks goofy
I'm moving left-up
package com.qookie.miner;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx.*;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.audio.*;
import com.badlogic.gdx.Input.Keys;

public class MinerMain extends ApplicationAdapter {
SpriteBatch batch;
SpriteBatch b;
private OrthographicCamera camera;
private float timer;
private int rand;
Texture img;
Texture map;
FreeTypeFontGenerator generator;
FreeTypeFontParameter parameter;
BitmapFont font;
private int speed = 250;
GameObject player;

@Override
public void create () {
    batch = new SpriteBatch();
    b = new SpriteBatch();
    img = new Texture("images/player.png ");
    map = new Texture("map1_fixed.png");
    generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/VCR_OSD_MONO_1.001.ttf"));
    parameter = new FreeTypeFontParameter();
    parameter.size = 10;
    parameter.color = Color.WHITE;
    font =  generator.generateFont(parameter);
    generator.dispose();
    player = new GameObject(img);
    camera = new OrthographicCamera(800,480);

}

@Override
public void render () {
    update();
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    //Normal rendering(map, player, objects, enemies)
    batch.begin();
        batch.draw(map,0,0);
        batch.draw(player.getTexture(),player.x,player.y);
    batch.end();

    // GUI rendering(always in the same spot on the screen)
    b.begin();
        font.draw(b,"0_01a",4,476);
    b.end();
}

public void update() {
    //batch.setProjectionMatrix(camera.combined);
    //camera.position.set(player.x+player.width/2,player.y+player.height/2,0);
    //camera.update();
    if(Gdx.input.isKeyPressed(Keys.W)){
        player.y += speed * Gdx.graphics.getDeltaTime();
    }

    if(Gdx.input.isKeyPressed(Keys.A)){
        player.x -= speed * Gdx.graphics.getDeltaTime();
    }

    if(Gdx.input.isKeyPressed(Keys.S)){
        player.y -= speed * Gdx.graphics.getDeltaTime();
    }

    if(Gdx.input.isKeyPressed(Keys.D)){
        player.x += speed * Gdx.graphics.getDeltaTime();
    }

    if(Gdx.input.isKeyPressed(Keys.ESCAPE)){
        Gdx.app.exit();
    }

    timer += Gdx.graphics.getDeltaTime();

    rand = MathUtils.random(10);
    batch.setProjectionMatrix(camera.combined);
    camera.position.set(player.x+player.width/2,player.y+player.height/2,0);
    camera.update();
}
@Override
public void dispose() {
    font.dispose();
    batch.dispose();
    img.dispose();
    b.dispose();
}
}

GameObject.java file:
package com.qookie.miner;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.math.*;

public class GameObject extends Rectangle {
private Texture txt;
public Texture getTexture() {
return txt;
}
public GameObject(Texture t) {
this.txt = t;
this.width = t.getWidth(); this.height = t.getWidth();
  }

}

Have you padded your player.png? My guess is that because it is not padded, OpenGL is trying to blend with the background

So what should I do @spectacularbob?

@spectacularbob I have added 'batch.disableBlending();' after 'batch.begin()' and it did nothing.

Looks like you found your answer, but this may be helpful: The way that OpenGL renders textures, it usually blends the outer pixels of a texture region with the surrounding pixels in the image. So if your sprite is surrounded by transparent pixels in the sprite sheet, it can produce a "gutter effect" where the edge pixels seem to be correct. To fix this, you can just copy the outermost pixels of a sprite outward to add a "padding" so that when OpenGl does it's blending it will blend with the right colors.

If I remember correctly, SpriteBatch stores it's own matrices. This means that when you do:
batch.setProjectionMatrix(camera.combined);
camera.position.set(player.x+player.width/2,player.y+player.height/2,0);
camera.update();

the camera should be updated first, then the projection matrix set after the update, instead. So instead I believe it should be:
camera.position.set(player.x+player.width/2,player.y+player.height/2,0);
camera.update();
batch.setProjectionMatrix(camera.combined);

This may be the cause of your problem, but I'm not entirely sure - good luck, and I hope this helps!


text:
How can I handle multiple force in Unity?
I'm trying to get my character to perform a "dash" where their x velocity increases rapidly and then falls over time. However, I'm also maintaining a constant x velocity so the character appears to be running at all times. The problem is trying to figure out when the dash should be considered finished. It can't be finished when the x velocity is equal to the running speed again, because other forces may be acting on the character.
It feels like all the information I need to figure this out is gone because it's all been calculated into the velocity vector, and the actual forces and where they come from are thrown out.
I've considered the following:
final = run + dash + other forces

But this means I couldn't use Unity's forces because I don't know what they're meant to act on(for example should a force pushing me down while I jump be applied to the jump velocity or the not?).
How can I determine how much force my dash should do and how much it should "undo" with the information given by Unity?

How much force should apply, it depends totally on your environment. What are the factors, I don't know.
But your undo thing can be achieve by Mathf.Clamp.
Suppose you have constant horizontal velocity of 5, then you can do something like,
....
Rigidbody _rb = GetComponent<Rigidbody> ();
....
_rb.velocity = new Vector3 (Mathf.Clamp (_rb.velocity.x, 5, 10000), 0, 0);

Here you can specify the minimum force, which is your constant force, and max, it is up to you, my recommendation is to keep this value high as 10000. By this you can apply AddForce and you character will be able to get back to your constant velocity.

But what if there's another force involved? For example, wind that blows the character backwards. Instead of the "non-dashing" velocity being 5 it is now, -3 for example, because the wind applies -8 horizontal velocity. How am I suppose to take this into account?

it has two perspective, you want to say that you are handling your constant velocity variable? For example you are changing that if wind blows your character?

You should be using AddForce multiple times with different modes as needed


text:
Always operate at Time.timeScale = 1?
How do I make a specific script always operate at Time.timeScale = 1 no matter what? I want it to override even when another script calls Time.timeScale = 0 for example.

Why? It sounds like you may be taking a wrong approach somewhere.

When you don't make use of rigidbody physics, just save a copy of the current timescale in a local variable and set Time.timeScale to 1 at the beginning of the method. At the end of the method, reset Time.timeScale to the backed up value.
void Update() {
     float oldTimeScale = Time.timeScale;
     Time.timeScale = 1.0f;

     // your code

     Time.timeScale = oldTimeScale;
}

Another caveat is that FixedUpdate will never be called when the time scale is 0.
You can also ditch Unity's timescale handling altogether and do your own by having an own timescale instance variable in every MonoBehavior and multiply it with Time.deltaTime whenever you use it. Again, this will not work with rigidbody physics because Unity controls these itself based on the global timescale.

Unfortunately, I'm using rigidbody physics.

I want something like this: GetComponent<Script>().Time.timeScale = 1 Is it possible?

@Fawq What you would need is GetComponent<Rigidbody>().Time.timescale. But Unity does not provide this. Likely because collisions between rigidbodies in different timescales is something the laws of Newtonian physics do not cover very well, because they do not happen in the real world.


text:
How to scale objects and tiles without doubling view port in gamemaker
How do I scale up tiles and sprites without acully making the view port larger than the acual view? I know that I can just scale up the images and the tileset but there must better alternative right? The reason why I dont want to make the port bigger is because then I get this kind of "pixel perfect" behaviour so 1 pixel on the image is one pixel on the screen (So it looks kind of choppy). I'm thinking I can use the draw event if there's no other alternative but how would I do that with the tileset?

Depends how you want to scale them up. You can scale objects when you're placing them in Rooms by just dragging out their corners (and maybe holding Shift to keep them evenly scaled). You might be able to do the same with tiles.
Otherwise, if you're looking to scale sprites in real time in the game, you can use the function draw_sprite_ext, and to scale tiles you can use tile_set_scale.


text:
Where is the GUI button press sound file for Minecraft?
I am making a custom modpack, and I need to change the GUI button press sound for my modpack, but I don't know where the sound file is for clicking the GUI button.

This question may have been already answered here: Minecraft sound(ogg) files disappeared in 1.8

Learning to better help yourself is a wonderful thing, it helps you the most! With most things programming, doing a simple Google search first is typically the best route.
Then there's the option of reading the documentation for the thing you're working on. Often they have helpful tutorials or manuals to help you. Once you find a good source for documentation, it's typically best to look there first.
Finally, you can ask a question on a forum specific to the thing you're working on (but remember to always search the forum for an answer before asking a new one!), or if your question is more general, on a site for more general development in the field you're working in.
Specifically for your question:

Sound directory (after 1.7.2)
The sound files in
  version 1.7.2 (specifically 13w42a) and above are scattered and hashed
  into different folders, which are located in:
Windows: %AppData%.minecraft\assets\objects
  Mac OS X:
  ~/Library/Application Support/minecraft/assets/objects Linux:
  ~/.minecraft/assets/objects

Copying my answer from Arqade.

How to find a sound file

Open \.minecraft\assets\indexes\<version>.json. <version> can be 1.7.10, 1.8, 14w25b, etc.
In the index file, you can find a organized list of assets and some informations(hash and size) about them. cave9.ogg for example,

"minecraft/sounds/ambient/cave/cave9.ogg": {
 "hash": "b463fa47816fe9a5dfe508093150e647403e4db6",
 "size": 27096
  }

has a hash value of b463fa47…. Remember first 2 digits(in this case b4).
The actual sound file is located at .minecraft\assets\objects\<first 2 digits>\ with a filename being a <hash> without any extension. For example, cave9.ogg is located at .minecraft\assets\objects\b4\ with a filename b463fa47816fe9a5dfe508093150e647403e4db6 without extension.

In your case the filename is click.ogg.


text:
Turn-based multiplayer animate moves from last turn
I'm trying to make a 2-player turn-based strategy game, using the Google Play Games APIs
According to the documentation,

As a match progresses, the current player can modify and store the game data on Google's servers. The other participants can then retrieve and update this data on their turn.

What this seems to be saying (sorry if I'm completely misinterpreting this; I've never played with the Play Games APIs before) is that, since each turn is just updating the game state data on the server, a round could look something like this:

Unit A is on Square 1, Unit B is on Square 3
[P1's turn] Player 1 moves Unit A to Square 2
[P1's turn] Player 1 kills Unit B with Unit A
[P2's turn] When Player 2 looks at the game, it shows Unit A on Square 2, and no Unit B

What I want is for both players to see the animation when Unit A moves, rather than Player 2 just seeing the new state and not the transition:

Unit A is on Square 1, Unit B is on Square 3
[P1's turn] Player 1 moves Unit A to Square 2
[P1's turn] Player 1 kills Unit B with Unit A
[P2's turn] When Player 2 looks at the game, it shows Unit A on Square 1 and Unit B on Square 3, then animates Unit A moving to Square 2 and killing Unit B

So basically each player gets a replay of the action from their opponent's turn before taking their turn.
I know it could be possible to do something like this by looking at the differences in position of a unit between turns, then animating the change; this, however, breaks down when you have something like an attack, where all you know is a unit was destroyed and wouldn't necessarily be able to infer which unit attacked and should be animated.
How would I go about implementing something like this?

In the same way you upload the new gamestate to google play's server, you can upload the previous one too.

Unit A is on Square 1, Unit B is on Square 3
[P1's turn] Player 1 moves Unit A to Square 2
[P1's turn] Player 1 kills Unit B with Unit A
[P1](Now you do) Upload the new game state -> (Change for)[P1] Upload the initial state and the new state.
[P2's turn] Download both states. Now, using the previous and the new state you can do all the animations.

I'm far from a Google Play Games API expert, but I'm looking at this from an outsider standpoint assuming you can transmit any sort of data back and forth. As you stated, for moving you could just calculate the differences for their positions and make an animation out of that; but attacks become more complex. The way I see it, you need to tell the other side when something happens. Say, for example:
Soldier 1; who has a position of (1, 2) destroys a unit at (3, 1) by using a grenade.
Using the highlighted pieces of information, you could send to the server "(3,1) killed via grenade by (1, 2)", which might look like in pseudo code
int playerDeath = DEATH_GRENADE;
Vector2D killer = (1, 2);
Vector2D victim = (3, 1);

And you could assemble an animation out of that. Using different variants of those three variables, you could also say that x unit moved.
int playerMoving = player5;
Vector2D startPos = (1, 2);
Vector2D endPos = (3, 1);

Then, when you break it down, it's quite simple.

At turn consists of (x) number of actions
An action consists of one of the possible "action data structures"
A list of actions (a turn) is sent back and forth to transmit the recent happenings

Of course, this is all a really rough outline; considering I've never used Google Play APIs, but this is how I would tackle this issue.


text:
Mesh disapears before out of fov
I use a C# script to move the vertecies of my quad around the world space.
It works perfectly fine, but when I move/ rotate the camera away, so it does not look at the position of the quad, the quad disappears.
I cannot change the size of the quad, since that would not work with my other scritps.
How can I force the camera to allway render the mesh of the quad?

I'm assuming you have reasons for moving the vertices rather than just transforming the quad so I won't point out how slow this way is =p.
What Unity is doing is called frustum culling, it basically checks the precalculated bounds of an object  to see if it's possibly on the screen and if not, just skips it entirely. This works fine except when the bounds don't match the vertices. That's what is happening here.
You can tell Unity to update the bounds via Mesh.RecalculateBounds, or if you have the information to do it without letting Unity brute force it's way through all the vertices you can manually update localBounds and related variables in the mesh.


text:
Convert a direction vector (normalized) to rotation?
Say i have something like this:
pos += glm::normalize(target - pos) //PLEASE NOTE: pos is a glm::vec3 and so is target

This makes "pos" translate towards "target", but what if i want to make my object to face "target"?

You find the angle of the vector with atan2, then use that angle to rotate the owner of the 'pos'.

It works fine on rotation of the y axis, but what about the x axis?

Oh, you're in 3d?

Indeed it is so.

Ok, what I had in my comment was good in 2d. It's a bit more complex in 3d because there is an 'up' vector that has to be taken into consideration.

Couldnt you use glm::lookAt() for this? (rather curious for the mathy part about why that wouldnt work)

Making a model always face a point is trickier in 3d than it is in 2d: the added dimension makes one wonder "what about the UP?".
This here assumes that you want your model to stay vertical as much as possible, and it uses the following coordinate system.
// z+    y+
// |    /
// |   /
// |  /
// | /
// |/
//  ¯¯¯¯¯¯¯¯¯¯¯¯ x+

This also assumes that the 'front' vector of your model is in x+ and that the 'side' vector is y+ (and of course, 'up' is z+).
glm::vec3 dirglm( dir.x(), dir.y(), dir.z() ); // dir is normalized

// find the angle about world-frame-z-axis
double angle = std::atan2( dir.y(), dir.x() );

// Make the rotation matrix around the vertical (z) axis, adjusts the 'yaw'
glm::mat4 glmrotXY = glm::rotate( angle, glm::tvec3<double>( 0.0, 0.0, 1.0 ) );

// Find the angle with the xy with plane (0, 0, 1); the - there is because we want to
// 'compensate' for that angle (a 'counter-angle')
double angleZ = -std::asin( (dir).z() );

// Make the matrix for that, assuming that Y is your 'side' vector; makes the model 'pitch'
glm::mat4 glmrotZ = glm::rotate( angleZ, glm::tvec3<double>( 0.0, 1.0, 0.0 ) );

object->setRotationMatrix( glmrotXY * glmrotZ );

This will cause a behaviour similar to the one of a camera in a 3rd person view kind of game (I'm thinking MMORPG style). It has the caveat that you can't have 'pos' directly above or below.

You just need the standard lookat function.
#include <glm/gtc/matrix_transform.hpp>

glm::vec3 const up(0.f, 0.f, 1.f);
object->setRotationMatrix(glm::lookAt(pos, target, up));

That’s all! Replace (0.f, 0.f, 1.f) with whatever you want your “up” vector to be.

If direction and up vectors are collinear, then you're in trouble. I think direction by itself is not enough to describe orientation in 3D space. So the answer is no, you can't just convert direction into rotation matrix.

"you can't just convert direction into a rotation matrix" somewhat contradicts the two other answers that show how you can indeed do that, with a little care in selecting an appropriate up vector. There isn't a universal or perfect way to do it due to the hairy ball theorem, but there are ways that are "good enough" for our needs in games.


text:
Solution for Shipping Optimized and Minified GLSL?
I've tried to find a reputable optimizing compiler for GLSL that takes source shaders, performs what optimizations it can statically assume, and outputs a minified GLSL file with optimizations, stripped local variable names, and unnecessary content like comments/extra whitespace.
The goal is to transpile GLSL into a portable, obfuscated source file that has been optimized enough so that local device compilers can optimize the shaders at game startup while still maintaining simple and readable GLSL for development.
I'm searching for a solution in my development pipeline in lieu of HLSL's precompiled intermediate representation or Vulkan's SPIR-V intermediate representation. Am I wrong in my assumptions about shipping shaders for OpenGL, is there a best practice for optimizing and shipping shaders with a release build?

Unity's ArasP has written an optimizer that could possibly do what you need: https://github.com/aras-p/glsl-optimizer
You could also save the driver's compiled shader binary using OpenGL extension GL_ARB_get_program_binary on the first run and use it on subsequent runs to reduce loading hitches. The binary is hardware and driver dependent so you can't ship those.

It looks very promising, but I would love to find something that has tested support for more recent versions than GLSL 1.1/1.2. GLSL 3.3 and 4.0 are six years old now, it would be fantastic if they had verified support for it.

I've played around with it for a bit now and I can say that it actually fairs pretty well with newer versions of GLSL and is the most mature GLSL I've seen thus far


text:
Water reflection xna
I'm actually trying to do the reflection map for my water component, but even following the riemer's tutorial about reflection map the formulas provided doens't work. http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series4/Reflection_map.php
I've read somewhere on the Internet that riemer uses Z-axis as UpVector, and I'm using the Y-axis instead.
So my system for now is somethink like this:
private void DrawReflectionMap()
{
        this.GraphicsDevice.SetRenderTarget(this.reflectionMap);
        this.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        if (this.CameraPosition.Y > this.Options.Height)
        {
            Matrix reflectionMatrix = Matrix.Identity;

            // Camera position
            Vector3 reflectionCameraPosition = this.camera.Position;
            reflectionCameraPosition.Y = -this.camera.Position.Y + this.Options.Height * 2;

            // Camera target
            Vector3 reflectionCameraTarget = this.camera.TargetPosition;
            reflectionCameraTarget.Y = -this.camera.TargetPosition.Y + this.Options.Height * 2;

            Vector3 cameraRight = Vector3.Transform(new Vector3(1, 0, 0), this.camera.Rotation);
            Vector3 invUpVector = Vector3.Cross(new Vector3(1, 0, 0), reflectionCameraTarget - reflectionCameraPosition);

            reflectionMatrix = Matrix.CreateLookAt(reflectionCameraPosition, reflectionCameraTarget, invUpVector);

            Plane _reflectionPlane = this.CreatePlane(this.Options.Height - 0.5f, new Vector3(0, -1, 0), reflectionMatrix, true);

            if (this.Options.Draw != null)
                this.Options.Draw(reflectionMatrix, true, _reflectionPlane);
        }

        this.GraphicsDevice.SetRenderTarget(null);
}

and there is my camera: http://pastebin.com/hK9fi5DV
When I run all of this, I got this:

As you can see, it seems the reflection map is not in the right side and when I move my camera, the reflection map also moves thru the edges of the texture...
Do you have an idea from where this problem could come?
Thanks.

your reflection map needs to be generated after the rest of your scene is rendered (eg render the sky, the terrain, and what not first), if you position the camera on the edge of a small patch of terrain and don't render the sky you will end up with an empty map (as designed) ... the idea is that you will never be on the edge of your world in a real game scenario

I don't have any skybox for now, I was wondering if I could only render the mountains on the water for a start, and the if I add a skybox or whatever I want, the reflection will to automatically the job for me. What I actually do is I generate my refraction and reflection map before everything. Like I draw my terrain with a different ViewMatrix and then set the old one for the real terrain

from what I recall (it was a long time ago though) you basically just render what you want on your reflection map to an texture but inverted (the viewmatrix you talk about) ... in short > render scene to reflection texture > render scene > render water using reflection


text:
Get world position of touch on objects
In my Unity3d game, I want to get the world position that was touched, when I touch a specific object, regardless of all objects that are in front of it.
How would I do that, I only know Camera.ScreenPointToRay(...), but for some reason that does not work properly?

OK - one cannot answer the question with the information I provided.
In order to determin the point, where the Ray hit the object, I used RaycastHit.transform.position (which refers to the Transform object that was hit) as opposed to RaycastHit.point (which refers to the Vector3 in world space, where the RaycastHit happened).

I've worked out a system that prints the position the mouse is hovering over. You will probably want to write a function that doesn't update every frame. When you click it spits out an Vector3 of the position in worldspace you are hovering over with your mouse in Screen space.
using UnityEngine;
using System.Collections;

public class check : MonoBehaviour
{
    void Update()
    {
        RaycastHit hit;
        // Cast a ray from the mouse position to the world
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //When the ray hits anything, print the world position of what the ray hits using hit.point
        if (Physics.Raycast(ray, out hit)  && Input.GetMouseButtonDown(0)))
            print(hit.point);
    }
}

You can now Instantiate GameObjects with Instantiate(yourGO,hit.point,Quaternion.identity);

Camera.ViewportToWorldPoint allows you to get the place you clicked on the screen as a point in world space.

Thanks, but I have a different problem. I tried to spawn objects where I click, but they only get spawned at one position (where the camera was at the start of the scene)
Might this be a problem with UI?


text:
Why does transforming a Vector3 by a Quaternion result in reversed Z?
I'm trying to transform the vector (1, 0, 0) by an orientation unit quaternion, which in XNA should be:
Vector3 v = Vector3.Transform(Vector3.Right, Orientation);

But this results in the Z value reversed from its expected value—for example, transforming Vector3.Right by Orientation (0.6532815, -0.270598, 0.270598, 0.6532815) results in the vector (0, 0.7071, -0.7071) when it should result in the vector (0, 0.7071, 0.7071).
I found another implementation here:
Quaternion o = Orientation;
Vector3 oV = new Vector3(o.X, o.Y, o.Z);
Vector3 v = 2 * Vector3.Cross(oV, Vector3.Right);
v = Vector3.Right + o.W * v + Vector3.Cross(oV, v);

But that results in the same problem. Reversing the Z value is trivial, but I'm worried that if I don't find a solution to this now the problem will manifest some other way down the road. Especially since, up until now, I thought I was playing by XNA's rules in my game engine (same coordinate system, same handedness).
For reference, this code I wrote does produce the expected result in my engine:
Vector3 v;
Quaternion o = OrientationGlobal;
double y = Math.Atan2(2 * (o.W * o.Z + o.X * o.Y), 1 - 2 * (o.Z * o.Z + o.Y * o.Y)); // yaw about global Z axis
v.Z = MathHelper.Clamp(2 * (o.W * o.Y - o.Z * o.X), -1, 1);
double m = Math.Sqrt(1 - v.Z * v.Z);
v.X = (float)(m * Math.Cos(y));
v.Y = (float)(m * Math.Sin(y));

What am I missing?

You are not showing the actual values for the vectors and quaternions you are using and obtaining. This would help.

@samhocevar Okay, I added an example. Like I said, the input vector is always (1, 0, 0) and the input quaternion is an arbitrary unit quaternion. The output vector's Z value is always reversed from what I expect.

It sounds like the handedness of your output coordinate system is opposite that of the code that's generating the quaternion.

Transforming vector (1,0,0) by quaternion (w=0.6532815, x=-0.270598, y=0.270598, z=0.6532815) does resut in (0, 0.7071, -0.7071). Your “expected result” seems wrong to me.

Both XNA and Fabian Giesen’s implementation behave correctly. Transforming vector (1, 0, 0) by quaternion (w=0.6532815, x=-0.270598, y=0.270598, z=0.6532815) does resut in (0, 0.7071, -0.7071). It also does in Unreal Engine, in my own quaternion implementation, as well as in Wolfram Alpha.
Wolfram Alpha also gives the 3×3 matrix equivalent of the quaternion. You can see that multiplying this matrix by (1, 0, 0) will also result in (0, 0.707107, -0.707107) since it’s trivially the first column of the matrix:
|  0         -1  0        |
|  0.707107   0  0.707107 |
| -0.707107   0  0.707107 |

There is most certainly a bug in your code above, since every other implementation basically disagrees with it, but it’s hard to understand where, as I have no idea how you derived the formulas. But the use of atan2 immediately followed by sin and cos indicates it was probably just some test code so I suggest you just throw it away and trust the XNA implementation.
Ultimately, the problem probably comes from how you build your quaternion. I’d have a look there.

Yep, my code was test code to see if I'd arrive at my expected result using terms I intuitively understand (the output vector is the direction an object is facing after Tait-Bryan yaw and pitch have been applied, and I'm fairly sure my formulas for yaw and pitch are correct because I successfully use them elsewhere in the engine). I'll try to find whatever bug is causing this.

For posterity...it ended up being a simple handedness issue, but only around the Y (pitch) axis. I had it stuck in my head that positive pitch increases Z and negative pitch decreases Z, which isn't true in a right-hand system. Lesson learned!


text:
How do I correctly shift arrays on a Tetris line clear?
I'm writing a Tetris clone in C++ and I am at the last stage, I need to delete a row when it is full. Once a piece falls it is stored in a boolean array grid[20][10]. For example I check which row is full (or true), if so I call a method deleteRow, where n is a number of row:
void Grid::deleteRow(int n)
{
  for (j = 0; j < WIDTH; j++)
   {
     grid[n][j] = false;
   }
}

Once the row is deleted I call moveRowDown:
void Grid::moveRowDown()
{
  for (i = 0; i < HEIGHT; i++)
   {
    for (j = 0; j < WIDTH; j++)
     {
       grid[i+1][j]=grid[i][j];
     }
  }
}

This does not work, and all of the pieces disappear. What logic am I missing?

When i is 0 you copy the row 0 into the row 1, then i is 1 and you copy the row 1 into the row 2, etc. The problem is that when you copy the row 1, it has already been overriden.
You probably also have a problem when i = HEIGHT because i+1 is out of bounds.
The solution would be to iterate from the bottom row to the top row (from HEIGHT-1 to 1):
for (i = HEIGHT-1; i > 0; i++)
{
  for (j = 0; j < WIDTH; j++)
  {
    grid[i][j]=grid[i-1][j];
  }
}

You are absolutely right! Thank you very much for explaining the logic behind it! I appreciate your time! Thank you again!


text:
How to display sprites on a 2D canvas, using Unity 5 and C#
I want to show a mini-map on the screen, but I don't have any idea to how to paint something in a panel on a canvas by code. The mini-map would look like this prototype I made some time ago, in Visual Studio.

I've tried instantiating a prefab image, but couldn't get it to work. I have two problems.
Firstly, I have 25 Image objects created in the scene, and 25 in the PlayerController script, but I can't get it to change the sprite. I am currently declaring them as follows:
public Image minimap0, minimap1, minimap2, minimap3, minimap4, minimap5,
        minimap6, minimap7, minimap8, minimap9, minimap10, minimap11,
        minimap12, minimap13, minimap14, minimap15, minimap16, minimap17,
        minimap18, minimap19, minimap20, minimap21, minimap22, minimap23,
        minimap24;

Lastly, I don't know how to change all 25 object sprites with a for loop, similar to the code that follows:
public void DrawMiniMap() {
    // mapXCord = miniMapPanel.transform.position.y;
    // mapXCord = 0;
    // mapYCord = 0;

    mapY = playerYPost - 2;
    int contadorArray = 0;
    Vector2 position = new Vector2 (mapXcord, mapYCord);

    for(int i = 0; i < 5; i++) {
        mapX = playerXPos - 2;
        string actualMiniMap = "minimap" + contadorArray;

        // mapXCord = miniMapPanel.transform.position.x;

        for(int j = 0; j < 5; j++) {
            position = new Vector2 (mapXCord, mapYCord);

            if (MapCreator.mapa [mapX, mapY] == 0) {
            } else if (MapCreator.mapa [mapX, mapY] == 1) {
            } else if (mapX == playerXPos && mapY == playerYPos) {
                if (playerOrientation == 'n') {
                } else if (playerOrientation == 'e') {
                } else if (playerOrientation == 's') {
                } else if (playerOrientation == 'w') {
                }
            }
            // mapXCord += 15;
            contadorArray += 1;
        }
        // mapYCord += 15;
    }
}

The map is stored in an array for checking positions.

--Edits added--

Under canvas create empty GameObject, add Image component, assign sprite to Image.sprite

if he is using a second camera for the minimap he will need to use Raw Image instead of Image.

No, the minimap will be a 5x5 grid displayed on a canvas, i will not use a second camera for that. Then, i should make 25 empty game objects and update them as I needed, or there is a better way for that? (the map itself is a grid, making a dungeon rpg game)

http://i.imgur.com/nFr6sDK.png the minimap would look like this (bottom right corner, this was done time ago in Visual Studio)

Then you will need 25 sprite objects. In UI terminology they are named Image. so right click on canvs ->UI->image. I suggest that you parent them to a single empty object that has a Grid Layout Group. This will allow you to easily set up the grind. After that you need to update the Images accordingly ofc.

Mm, this is like basic steps you have to do either manually or programmatically. When doing manually you can also create image with GameObject > UI > Image, then drag and drop the sprite on it in Inspector. If you are doing this at runtime you can create a prefab of your Image GameObject and use Instantiate() function to spawn them.

Uri's way is the way to go, I was going to make the next comment like his. :))

I can't make this to work! Have two problems, I have 25 Image objects created in the scene and 25 in the playercontroller script http://imgur.com/Lxrdplj , but I can't make to change its sprite, and also, I don't know how to change all 25 objects sprite with a "for" loop (the foor will look like this http://imgur.com/qfi1Ht1 ). The map is stored in an array for checking positions.

This is a seperate question please make a new question about iterating over 25 game object and I will explain how to do it.

http://gamedev.stackexchange.com/questions/120611/how-to-iterate-over-25-sprite-objects-unity-5-c here it is


text:
How to iterate over 25 Sprite Objects (Unity 5 - C#)
I wanna show a minimap on the screen. The minimap would look like this (bottom right corner, this was done time ago in Visual Studio):

Have two problems with that, I have 25 Image objects created in the scene and 25 in the playercontroller script:
public Image minimap0, minimap1, minimap2, minimap3, ... , minimap24;

but I can't make to change its sprite, and also, I don't know how to change all 25 objects sprite with a "for" loop (the foor will look like this https://i.stack.imgur.com/cpCLN.jpg ).
The map is stored in an array for checking positions.

Are you familiar with arrays, eg. public Image[] mapTiles or Image[,] mapTiles = new Image[5, 5]?

It's really great that you want to add code to your question, but it would be far better when you would put it into the question as text and not post it as an image. That way people can directly copy&paste your code into their answer and correct any mistakes.


text:
Tetris implementing rotation
I am currently at the last stage of the Tetris Clone using SDL library, the only thing left is rotation. For each piece I have a separate class, and in order to move the pieces down I use a method:
void PieceZ::movePieceDown()
{
  drawBlock(x1,y1++);
  drawBlock(x2,y3++);
  drawBlock(x3,y3++);
  drawBlock(x4,y4++);
}

This method is called like that: current->movePieceDown(); where current represents a pointer to the current piece. Now to rotate the piece I have another method:
void PieceZ::rotatePiece()
{
  drawBlock(newX1,newY2++);
  drawBlock(x2,y2);
  drawBlock(newX3,newY3++);
  drawBlock(newX4,newY4++);
}

New X and Y coordinates are calculated elsewhere, with x2 and y2 taken as the origin.
My question is how do I swap current->movePieceDown() with current->rotatePiece() while the piece is moving? Taking into acount that I am handling keyboard events in another method.

I found a solution, I am posting it just in case. Basically I removed the method rotatePiece(), instead of that I have a method that calculates the rotation independently of drawing:
void PieceZ::getRotation()
{
  newX1 = (y1-y2) + x2;
  newY1 = (x2-x1) + y2;

  newX3 = (y3-y2) + x2;
  newY3 = (x2-x3) + y2;

  newX4 = (y4-y2) + x2;
  newY4 = (x2-x4) + y2;

  x1 = newX1;
  x3 = newX3;
  x4 = newX4;

  y1 = newY1;
  y3 = newY3;
  y4 = newY4;
}

new values are set to 0 initially, and every time a user presses a button on the keyboard this method gets called, it calculates the new rotation in new and assigns it to x and y values. Which gives you a 90 degree counter clockwise rotation.

Alternatively, you could store four different pre-defined rotations and swap amongst them.

That's true. But that would envolve having hard coded arrays instead of coordinates.


text:
The best way to store and protect game data
I'm writing a sandbox-type game and i'm looking for a good way to store game data. I tryed Lua and plain text files, but the have a big minus - player can edit them his self!
So how do I protect data from player? Thank you!

Why would you do that anyway? When it's a multiplayer game, anything worth editing should be on the server. When it's a singleplayer game, why do you want to prevent the modding community from adding value to your game?

You can store the game data in a file, and obfuscate the data if you do not want the player to modify the stored values.
This would be done by encrypting your data, and then decrypting it when you load it up in your game.  The encrypting / decrypting would be hard coded into your binary.
That being said, if someone wants to get at the game data, there will be attempts at cracking your encryption technique, and publish a hack.  You can try to prevent the data from being hacked, but you cannot stop it entirely.

Thank you! Can you give me an example of encrypting / decrypting, please?

I am not up to date with C++ so I would not be good to suggest what to use.  You should just do a google search on encrypting text, text obfuscating.

This question is actually a duplicate, see comment in your question above.

You can't.
If your game is a single player game or not connected to the internet, and you don't have them use any kind of DRM that big companies can have (Ubisoft, EA, Blizzard and the like), users will find a way to hack in your data and modify them.
There are ways to obfuscate it, and make their life harder, but ultimately, someone motivated enough will find a way to reverse engineer your data (savegame or assets), make an editor, and change the content of your game.

But can I make it unreable (inexplicable) for users? That's what I meant.

As I said, you can't. You can only make it harder for them to read and understand it.

Yes, you can, but thats an idiotic hard work, you could encrypt it and make your game interpretate the encripted string instead of trying to decrypt it, that would have no sense and hackers wouldnt be able to read or modify it. But seriously, do you need that level of nonsensenes?


text:
What is the difference between Sprite and SpriteBatch, specifically in the context of libGDX?
I'm using libGDX and I'm confused about the difference between the Sprite and SpriteBatch.
Anybody can explain it to me in a simple way?

A Sprite is simply a data structure that contains information on how and where to draw a texture (i.e. position, color, texture handle, rotation, scale).
Because of the way that OpenGL works, it is best to group or "batch" draw calls together to get the optimum performance. This grouping is why you will get an error if you try to draw to a Batch without first calling batch.begin() as this signals the Batch to start the work of grouping draw calls. When you call draw() on a batch, it isn't actually doing the work of drawing yet, it is only organizing the data you give it. It will wait to draw to the screen until batch.end() is called.
A SpriteBatch is a Batch which is used for drawing Sprites, more specifically, it deals with drawing a bunch of textures on Quads in OpenGL. In a SpriteBatch there is a lot of interaction behind the scenes with OpenGL that, thankfully, we don't have to do manually. There are a few parameters that SpriteBatch shares among all the sprites that are drawn to it, namely: projection and transformation matrices, tint color, shaders and blend settings.
You don't actually have to use the Sprite class to use a SpriteBatch. You can just give your own parameters to any of the draw calls that SpriteBatch provides. For convenience, the Sprite class has a draw(Batch batch) function that will forward all of the data in the Sprite to the approriate draw calls in the Batch

A Sprite is a single sprite, whereas a SpriteBatch is a collection of multiple sprites, all drawn using the same settings.


text:
How to check the memory leackage in libGDX game development?
I'm developing a multi-platform game in libGDX. Sometimes there is a huge issue with memory. The game used to stick a lot. In fact, I even used pooling.
Is there any method to check the memory leakage in libGDX?

The JVM will never give memory back to the operating system after it allocated it, so if you're checking memory usage in the task-manager it might be just a peak in memory-usage some time ago, but the JVM still holds onto the free memory.

You can use a memory profiler like JProfiler(trial/paid) or JVmonitor(free) to take a snapshot of the heap when your program starts to eat up memory. These programs will at the very least tell you what type of object is eating up your memory. These of course will only work for the Desktop version of your app.
Also ensure that you are using pooling correctly. Specifically, the moment that you are done with an object created from a Pool, make sure you call free() on that object. Otherwise the next time you call obtain() the Pool will create a new object.
Also see if there is anywhere in your code that you are thrashing a pool. Meaning, if you call obtain() 1500 times in a row, then you will create 1500 objects. These objects will stay in memory until you clear the pool (depending on the max setting of the pool). You may want to redesign that part of the code so that you don't hit the pool so hard all at once.
Check out the Memory Management page of the libgdx wiki. It has a list of all the objects that must be disposed when you are done with them. If your game changes states/screens a lot, make sure that the resources you no longer need from a state gets disposed between states.
If you aren't already, make use of the AssetManager class. It uses reference counting so that everything you load can be shared between all users that need it. This is critical for large unmanaged objects like textures. This also means that once the reference count drops to 0, AssetManager will dispose of the asset for you.


text:
Reynold's Steering Behaviors
So I read Reynold's 1999 paper, [Steering Behaviors For Autonomous Characters][1], and I presume something went over my head, because it doesn't seem to make any sense to me.

steering_force = truncate (steering_direction, max_force)
acceleration = steering_force / mass
velocity = truncate (velocity + acceleration, max_speed)
position = position + velocity

Not sure how this makes any sense. Unless there's a constant time step of 1s, this integration (a forward Euler, which is bad in it's own right), doesn't make much sense to me.
The behaviors themselves don't seem to make much sense either:
Seek:

desired_velocity = normalize (position - target) * max_speed
steering = desired_velocity - velocity

The desired_velocity is in the wrong direction? Should be (target - position)? It also doesn't return a force - it returns a difference of velocities. It doesn't scale at all with mass.
Arrival

target_offset = target - position
distance = length (target_offset)
ramped_speed = max_speed * (distance / slowing_distance)
clipped_speed = minimum (ramped_speed, max_speed)
desired_velocity = (clipped_speed / distance) * target_offset
steering = desired_velocity - velocity

This just doesn't make any sense to me. This will flat out not work. Sure, you'll eventually get a vector pointing away from the target, but depending on the vehicle's mass, may not be able to stop it in time. It's also dependent on an arbitrary slowing radius not tied to the objects max thrust, max speed, or mass. Like Seek, it also doesn't actually return a force.
I stopped reading after that. Clearly there is something I am missing here..

Did you have an issue you were trying to resolve? How about a specific question? Sounds like you're trying to start a discussion over a 17 year old paper. There are other resources out there if you're looking to implement steering.

@Byte56 Clearly I'm missing something big and obvious in the paper. There are tons of tutorials and books that reference this paper - so they can't all be wrong. I just don't understand what I'm missing here. Like every steering reference I've come across has been based on this paper.

The paper is a simplified model that can be taken, modified and implemented into your specific situation. It's not intended to be an implementation you copy/paste into your game.
There are a few instances where the simplification is brought up, like when speaking about the simplified vehicle model:

This vehicle model is based on a point mass approximation. On the one
  hand that allows a very simple and computationally cheap
  physically-based model (for example, a point mass has velocity (linear
  momentum) but no moment of inertia (rotational momentum)). On the
  other hand, it cannot be a very compelling physical model because
  point masses do not exist in the real world. Any physical object with
  mass must have a non-zero radius and hence a moment of inertia. This
  use of an oversimplified non-physical vehicle model is merely for
  convenience and intended to be “without loss of generality” — it
  should always be possible to substitute a more plausible, more
  realistic physically based vehicle model.

Emphasis mine. Basically, don't assume the algorithm presented will fit directly into your model. If you need a algorithm that's been adapted to fit something closer to the model your expecting, search for implementations of the steering algorithms in the engine of your choice.

"This vehicle model is based on a point mass approximation." - but it doesn't work for a point mass approximation.

Looks like the mass is factored into the maximum speed


text:
Configuring Implicit Multi-GPU Rendering Driver Settings Programmatically
What is available to game developers to take advantage of implicit multi-GPU rendering technologies as of 2016? For this question I will only be asking about Nvidia's SLI and AMD's Crossfire technologies as they apply to rendering in OpenGL and Direct3D, specifically non-ancient versions of these APIs like OpenGL core 3.3+ and Direct3D 10.0+.
What tools do developers have access to, to programmatically detect and alter the state of implicit multi-GPU rendering for their game?
A key component of this question is what is openly available to independent developers, SLI and Crossfire aren't problems to AAA developers who get GameReady drivers tweaked to enhance the performance of their game and have SLI profiles included within the driver. What is available for smaller developers to take advantage of multiple GPUs?
At the very least, is there anything that developers can do to reduce the negative effects that these technologies can cause? Is there a way to avoid a FPS drop or artifacts that come with SLI/Crossfire bugs, can a developer programmatically disable SLI or Crossfire?
With all of this, how is the cross-platform support? Is there a solution for these issues that will work across Windows, Linux, and OSX? Will it work with OpenGL and Direct3D? Can it run out of the box or packaged with your game?

With all the research I've done on this topic looking for modern solutions, this is as much I could find available to independent developers available as of early 2016 for SLI and CrossFire:
Windows + CrossFire + AGS for Direct3D (Allows for some explicit control)
I was really impressed with what AMD had done for Windows with their AMD GPU Services API which allows for explicit control over CrossFire configuration on GCN-based (HD 7000+) GPUs when using Direc3D 11. They have good documentation, a getting started guide, and samples.
Windows + CrossFire for OpenGL and Direct3D
You don't get any explicit control, but there are things you can do to make your game more friendly for CrossFire Alternate Frame Rendering, even for OpenGL. They have a couple guides on optimizing your game for AMD GPUs and CrossFire. You may be able to increase the performance of your game just by requesting that the AMD drivers try to use CrossFire AFR on your game be renaming the executable to AFR-FriendlyOGL.exe or AFR-FriendlyD3D.exe.
Windows + SLI + NVAPI for Direct3D
The Nvidia NVAPI allows developers the ability to query some information about the current SLI configuration and use that information to better configure their rendering engine. Functions like NvAPI_D3D_GetCurrentSLIState allow you to query some information about the SLI AFR configuration if you are using Direct3D 10+.
Windows + SLI for OpenGL and Direct3D
Nvidia provides a best practices guide for SLI AFR (Alternate Frame Rendering) and SFR (Split Frame Rendering). Which appears you can influence the Nvidia drivers in a similar way as the AMD drivers by renaming your executable to AFR-FriendlyD3D.exe. There is also, the Nvidia GPU programming guide which will help you optimize your game for Nvidia GPUs which will naturally help your SLI compatibility and performance as well.
Linux + SLI or Crossfire for OpenGL
Nvidia and AMD are on a fairly equal playing field here. SLI and CrossFire are practically impossible to get working even for AAA titles, it takes a lot of user configuration to get SLI or CrossFire working slightly. In most cases performance goes down or introduces terrible graphics issues when SLI or CrossFire are enabled. Implicit multi-GPU support just doesn't work here yet, at least not consistently enough for you to depend on it for your game. This is an issue that I hope to see change soon in the future as many enthusiasts and VR users are making a move to Linux and SteamOS to tinker in a more open space.
Mac OSX + SLI or Crossfire for OpenGL
Support for this is worse than on Linux for the most part, but it doesn't seem like it will be a necessity. The cheapest computer running OSX with two GPUs starts at $3,000 USD and ships with two workstation GPUs (FirePro) realistically anyone looking to spend that much money on a computer for games isn't going to buy a mac in the first place.
In closing, multi-GPU support for games today isn't great but it's getting easier to build games for enthusiast grade hardware, and if you really care about getting that much more performance APIs like Vulkan and Direct3D 12 look like they will provide some great explicit multi-GPU support.

It would seam that basic concurrent processing techniques would be paramount for implicit multi-gpus. Making sure to avoid f'( f( null, 0 ), dt ) type updates, where the next frame is computed based on the immediately previous frame, would go a long way to increasing the programs efficient utilization. The biggest challenge would appear to be querying the system to find out how many cards are being used so that algorithms can be adjusted accordingly.


text:
Calculate XP needed for next Level using this simple algorithm?
I am currently calculating the Levels in my game using the following forumla:
player.level = mathFLOOR(mathMAX(1, 0.05 * mathSQRT(player.score)) * (1 + player.kd / 10));

So the level is based on the persons total score and their kd. However I am now trying to figure out a formula for calculating the percentage of the score/kd you need to progress to the next level. If this is not possible, how could I do it with just this formula:
 player.level = mathFLOOR(mathMAX(1, 0.05 * mathSQRT(player.score)));

Thank you for your time.

Unless I missed something here doing this ...
var progress = 0.05 * mathSQRT(player.score)) * (1 + player.kd / 10);

... will get you a value of how far the user has "progressed".
The level is that value rounded down to the nearest integer or 1 with ...
player.level = mathFLOOR(mathMAX(1, progress));

.. the progress between the current level and the next is therefore something like ...
var toNextLevel = progress - player.level;

... that will give you something like 0.1 for 10% or 0.34 for 34%

Wouldnt that just give me the difference by which the level was floored? Because essentially you are making the level = progress. The mathMax(1, ...) is just to make sure you are never below level 1.

level is essentially the round number or whole integer values of progression, the progress on the current level is the bit after the decimal place or the remainder converted to a percentage. To answer your question, yes this basically is the difference by which level is floored. Is that not what you were after?


text:
Vulkan vkEnumeratePhysicalDevices Returning Unexpected Device Count
In the machine I'm running I have two GTX 980 Tis.
When I query the physical device count with vkEnumeratePhysicalDevices it always returns 1 despite having 2 physical discrete graphics cards. When I use vulkaninfo the only device listed is GPU0 which is a DISCRETE_GPU / GTX 980 Ti.
This happens in Windows 10 as well as GNU/Linux 4.5 using Vulkan API 1.0.11 with proprietary Nvidia drivers.
Is this normal behavior and I'm not using the API correctly or is this a bug? I feel like I've made a glaring obvious mistake but I can't find anything in the Vulkan specification about it.
For clarity, this is exactly how I query physical device count:
auto deviceCount = uint32_t{0};
instance.enumeratePhysicalDevices(&deviceCount, nullptr);
// At this point deviceCount is 1

Also, to confirm that the OS sees the cards:
Windows 10:
C:\Users\matt>wmic path win32_VideoController get name
Name
NVIDIA GeForce GTX 980 Ti
NVIDIA GeForce GTX 980 Ti

Linux 4.5:
+------------------------------------------------------+
| NVIDIA-SMI 364.19     Driver Version: 364.19         |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 980 Ti  Off  | 0000:01:00.0      On |                  N/A |
|  0%   56C    P8    34W / 300W |    444MiB /  6140MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 980 Ti  Off  | 0000:02:00.0     Off |                  N/A |
|  0%   43C    P8    25W / 300W |     22MiB /  6143MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

Integrated GPU is often (?) inactivated by the motherboard if a discrete GPU is found. Is it visible in the device manager?

That's not a factor here, I don't care about the integrated GPU, only the discrete GPUs.

Ok. Are you able to display anything using both discrete GPU:s?

Yes, of course, I've attached more information to show that both Win10 and Linux are picking the cards up. I've used both of the cards for CUDA as well as SLI with Direct3D and OpenGL.

You should pass NULL as last parameter, not nullptr. Won't fix it I think but it is worth a shot.

I'm using vk_cpp.hpp as a C++ wrapper around vulkan.h using G++ 5.3.0 and Clang++ 3.7.1 with the std set to C++14, nullptr is the correct usage for this and NULL will make no difference. Not only that, but given that vulkaninfo only provides one GPU I'd guess that this is a global issue with configuration less to do with the semantics of how I pass a nullptr, plus the deviceCount doesn't change (by design) when I call vkEnumeratePhysicalDevices again to populate the list of GPUs with actual PhysicalDevice instances.

@Andreas nullptr and NULL differ only in that NULL can be misinterpreted as an integer literal, they're both interpreted as null pointer constants in a pointer context.

@LarsViklund True. My point was the vulkan reference states the parameter shall be NULL. It does not say it shall be null pointer :) If there is risk of misinterpretation it is so by design by the smart people at Khronos. https://www.khronos.org/registry/vulkan/specs/1.0/man/html/vkEnumeratePhysicalDevices.html

@Andreas, that's just simply not how this works in C++, I don't mean to discount your opinions, but this is just a completely irrelevant argument to the question at hand.

You do not use the function according to the API reference. Look I'll prove my point elsewere. This is not the place. Good luck finding the problem. (Which I can't imagine is because of the null pointer just to be clear)

You need to have drivers for both GPUs installed.

@ratchetfreak what leads you to believe I don't? I've already said they both work together quite well, is there further configuration to be done?

From the LunarG FAQ:

There is no multiple GPU support in version 1.0. That was unfortunately a feature Khronos had to cut in order to preserve
  schedule. It is expected to be near the top of the list for Vulkan
  1.1. It is perfectly possible for a Vulkan implementation to expose multiple GPUs. What Vulkan currently can’t do is allow resource
  sharing between them. So from a point of view of, for example, a
  Windows system manager, its possible to recognize multiple ways to
  render to a surface and then use operating system hooks to transfer
  that to the screen. What Vulkan doesn’t have is the ability to share a
  texture or a render target between multiple GPUs.

I'd write this issue off as being something that wasn't implemented because it wasn't required that they implement it yet. When Vulkan adds better multi-GPU support to be required in their spec these issues will most likely be fixed. It is odd that it still won't expose the GPUs available, but even if it did, Vulkan 1.0.x isn't ready for utilizing multiple GPUs in a way that would benefit games.
Update as of 7/23/2016: With Nvidia GeForce driver v368.69 multiple GPUs are visible to Vulkan.
Without changing anything (still using Vulkan API v1.0.11) and updating to Nvidia's latest driver, I have full access to both physical devices on my machine, this doesn't mean that Multi-GPU support is quite here, but it's the first step in Vulkan even being a viable choice when developing a game.

You should've disabled/removed the SLI bridge.
That's the glaring obvious mistake I'm seeing here AFAIK.

That has absolutely no bearing on it, see my answer, it has been solved.

@MattJensJensen At the time of this question, NVIDIA's implementation was showing the SLI combo and not individual cards, that's what I'm referring to.

No, it wasn't for me, without the SLI bridge, only one card was visible.


text:
How to handle global Data within a state machine setup? (C#)
I am currently building a turn-based framework (Unity,C#)
I was tired of my former tight-coupled systems and opted for a state machine this time, basically all components subscribe to the state-Enter and state-Exit event. I am aiming for scalability and structure.
But I ran into a problem. If the components cannot communicate directly, how to store and forward data in between states?
Example: The game starts with unit placement. The player has the option to select a unit in his pool via the ui and place it on the board.
The Unit-creation logic is and should(?) be handled inside the level script. How does it know where to create which unit?
Ive done a workaround with a static container class, with is basically my clipboard. The player assigns a grid cell for his selected unit and the game leaves the state.
While leaving the state the level scripts scans the clipboard and creates any assigned units.
But I feel like a cheated my attempt to really work strictly within a firm structure this time to guide the design process.
Is there a better way?

A fine way to handle in a discrete way communications between entities is the Oberver pattern. Take a look at it.

I just impletented a simple version of the observer pattern. But how do I get a reference of the observing object? I need it to add it as an observer to the list.

better if I write an answer

Yes, setting a global variable and then calling a method which behaves differently based on its value is a dangerous anti-pattern known as "Accumulate and Fire". The remedy is to pass all data which is required by a method as parameters.
In your case the solution is to not use generic event handlers to enter a state. Give each state an unique Enter method with unique parameters which takes the arguments needed by that state and call these methods directly.
For example, StateSelectUnit switches to StateGiveCommand by calling StateGiveCommand.Enter(selectedUnit). The semantic is that you do not enter a generic StateGiveCommand, you enter a specific StateGiveCommand for that unit, which is a different state than giving a command to a different unit.

I like this. If I understood it correctly each state has a data structure as a  "result" which can be used by the following state?

@openend Not necessarily one result. The parameters for an Enter method of a specific state could be any number of parameters, including none. But generally yes, each state would pass everything to the next state it needs to know.

Thanks! I ditched the state machine entirely (for now) and went with delegates only, since I can do a simple Event-> Reaction setting. Maybe this will work out. Thanks for answer, it inspired me to really think about what information I need where and when.

A fine way to handle in a discrete way communications between entities is the Oberver pattern. Take a look at it.
each entity who need observation will need to add an observer to its list
public void AddObserver(Observer o)
{
    obs_l.Add(o);
}

Then when you define your Notify function you will baasically pass a reference to the object calling, if it is your need. Take a look of a sample of my Notify function:
protected void Notify(Object entity, KCEvent e, Object target, List<float> f_args, Vector3 pos, Quaternion rot)
    {
        foreach (var o in obs_l)
        {
            o.OnNotify(entity, e, target, f_args, pos, rot);
        }
    }

this is because when I notify observers what is happening I need to make them aware of a few things, like:

entity, the Entity which notifies the event
e, the event (just an enum in my case)
target, another entity where the event could happen on
f_args, a list of float which represent different data needed by the observer to do things
pos, is a position vector where things could happen
rot, possibly a rotation needed to apply to something

All of these are purely chosen on my needs. You will do the same.
To answer you comment when I call Notify I will pass this as first parameter.

Thats exactly what I did. But from where would you call the method AddObserver? The observed object does not know the observer and vice versa. If they would, they would be tight coupled again.

Actually you can do that in the Awake() method of your observed object, or whereever you initialize it.

I am really sorry, Leggy, but you can't. I appreciate your effort, but I tested your solution, and tried different implementations of the observer pattern. It may be due to my limited abilities, but I think this does not work in Unity. I cannot use the Awake() method, I have no reference to the object I want to observe.

whether the object is a monobehavior or another class you have either the Awake() method or an Initialization method for that object. whereever you do that you add the observer to the list that your object obviously has

I think you do not understand the problem. Of course I have a method in which I could add things to a list. But I have no reference to these things.

hmm, Maybe. But what holds you from doing in your object initialization something like this:
AddObserver(GameObject.FindGameObjectWithTag("Observers").GetComponent<GraphicObs>());
?

Thanks. That could actually work out (I think). Ill test it out, if my current approach fails.


text:
LibGDX Rotate 2D image with touchDragged() event
Objective: to rotate an image in the center of the screen with movement equal to left or right touchDragged event.
Right now I have a basic Stage that is created and adds an actor (centerMass.png) to the stage. it is created and rendered like this:
public class Application extends ApplicationAdapter {
Stage stageGamePlay;

@Override
public void create () {
    //setup game stage variables
    stageGamePlay = new Stage(new ScreenViewport());
    stageGamePlay.addActor(new CenterMass(new Texture(Gdx.files.internal("centerMass.png"))));

    Gdx.input.setInputProcessor(stageGamePlay);

}

@Override
public void render () {
    Gdx.gl.glClearColor(255f/255, 249f/255, 236f/255, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    //before drawing, updating actions that have changed
    stageGamePlay.act(Gdx.graphics.getDeltaTime());
    stageGamePlay.draw();

    }
}

I then have a separate class file that contains the CenterMass class, extending Image. I am familiar enough to know I could extend Actor, but I am not sure the benefit I would gain using Actor vs Image.
In the CenterMass class I create the texture, set bounds, set touchable and center it on the screen.
Inside CenterMass class I also have an InputListener listening for events. I have an override set for touchDragged where I am trying to get the X and Y of the drag, and use that to set the rotate actions accordingly. That class looks like this:
//extend Image vs Actor classes
public class CenterMass extends Image {
public CenterMass(Texture centerMassSprite) {
    //let parent be aware
    super(centerMassSprite);
    setBounds(getX(), getY(), getWidth(), getHeight());
    setTouchable(Touchable.enabled);
    setPosition(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
    setRotation(90f);

    addListener(new InputListener(){
        private int dragX, dragY;
        private float duration;
        private float rotateBy = 30f;

        @Override
        public void touchDragged(InputEvent event, float x, float y, int pointer) {
            //get
            float dX = (float)(x-dragX)/(float)Gdx.graphics.getWidth();
            float dY = (float)(dragY-y)/(float)Gdx.graphics.getHeight();

            duration = 1.0f; // 1 second

            Actions.sequence(
                    Actions.parallel(
                            Actions.rotateBy(rotateBy, duration),
                            Actions.moveBy( dX, dY, duration)
                    )
            );

        }
    });
}

@Override
protected void positionChanged() {
    //super.positionChanged();
}

@Override
public void draw(Batch batch, float parentAlpha) {
    //draw needs to be available for changing color and rotation, I think
    batch.setColor(this.getColor());
    //cast back to texture because we use Image vs Actor and want to rotate and change color safely
    ((TextureRegionDrawable)getDrawable()).draw(batch, getX(), getY(),
            getOriginX(), getOriginY(),
            getWidth(), getHeight(),
            getScaleX(), getScaleY(),
            getRotation());
}

@Override
public void act(float delta) {
    super.act(delta);
    }
}

The Problem:
I have not been able to get it to rotate the way I would like. I have been able to get it to shift around in unpredictable ways. Any guidance would be much appreciated.

Actions.sequence() is a convenience method to create a SequenceAction object. You have to give this action to your Actor for it to do anything.
//addAction() is a member of Actor
this.addAction(Actions.sequence(...))

However, this is probably not what you want. Firstly, a SequenceAction is an action where it waits for each action to finish before the next action is applied. To execute both at the same time, you don't need the sequence() or parallel() calls, just
this.addAction(Actions.rotateBy(rotateBy, duration));
this.addAction(Actions.moveBy( dX, dY, duration));

They will execute in parallel and remove themselves when they have finished after duration seconds.
That being said, you might not want to use actions in the first place As your code is now, you will add Actions to the image actor each time that the touchDragged() event fires, regardless of whether the prior Actions have completed. You could wait until the Actions are finished (via Actor.hasAction()) or clear the existing Actions from the Actor before re-adding them. Or you could forgo adding any Actions at all and have your touchDragged() event directly move and rotate the image.
P.S. There really is no reason at this point to inherit from Actor since Image already inherits from Actor


text:
Level/Asset design for performance Unity
I am a big fan of modular assets.
Currently I am designing a 3d game for mobile and I don't know how I should create my levels to get the most out of the device.
Should I...
create lots of "small" (1x1x1 meter) assets and build my level using them
or create one geometry for the entire level?
What about textures?
Should "all" objects share one highres texture and only display their part using the right UV settings (like say in minecraft)or should I create an individual texture for each object?

There are lots way of optimization including

LOD - hig and low poly object display according to camera
Culling - show only camera frustam obects
mesh combine - combine meshes
World streamer (dividing scene into sub-scene then load/unload according to camera position)

Maybe what you are talking about is the fourth option divide your scene into multiple scene using this package and enjoy good performance.
Remember: before purchasing any package you need to carryout some research according to your requirements

I am torn between mesh combine and culling. My game would have hundrets of static objects with a similar geometry, but different textures. Think of a static minecraft level. :)

then use mesh combine and texture combine

http://stackoverflow.com/questions/25545506/combine-array-of-sprite-objects-into-one-sprite-unity


text:
How can I register Mouse Events in the Scene window of the Editor?
I want to create a custom level editor for the level designers that should allow them to place predefined objects in Unity3d similar to the Terrain wizard.
How can I register Mouse Events in the Scene window of the Editor?

This does of course not answer your question, but in my current project I integrated the map editor into the game itself. So in order to edit a map, the mapper plays it in the game and then clicks on a "Map Editor" button which will be hidden in the release build.

That's a nice concept. However I can't give up the full feature set of the Unity Editor and I sure as hell ain't gonna reimplement all of it! ;)

Perhaps this is something you are looking for. This allows you to register mouse events in the scene, when a game object with the specified type is selected in the hierarchy.
using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor(typeof(SomeScriptType))]
public class MyEditorPlayer : Editor
{
    void OnSceneGUI()
    {
        int controlID = GUIUtility.GetControlID(FocusType.Passive);

        switch (Event.current.GetTypeForControl(controlID))
        {
            case EventType.mouseDown:
                GUIUtility.hotControl = controlID;
                Debug.Log("MouseDown");
                Event.current.Use();
                break;

            case EventType.MouseUp:
                GUIUtility.hotControl = 0;
                Event.current.Use();
                break;
        }
    }
}

You only need to add the [ExecuteInEditMode] attribute to your class to run events in edit mode:
[ExecuteInEditMode]
public class myclass: MonoBehaviour
{
    void Update()
    {

    }
}

I know, but I want to only process Mouse Events in the LevelEditor window.

How i tell you can do it with ExecuteInEditMode, add only your mouse event/s in the class and you got.

I can see what your trying to say, but it is clear that others do not. Perhaps you should expand upon your answer?


text:
AI: Turn-Based Movement with 2 actions per Unit
I am currently building a turnbased tactics game.
The Board is a small (about 4*6) tiled grid.
The AI plans all moves of its units, each unit can

move 2 times
move and attack
or attack

at least in this basic stage.
Only one unit can be on a grid cell at any given moment. But a Unit can take a turn to a grid cell which was just left by the former occupant.
The AI plans out the whole turn in advance, and then the actions is played.
The Mission: The AI should maximize the attacks for each round. Currently only Melee is implemented, so this means maximize the count of own units in the grid cells next to the player units, and they should have a turn left to attack, if possible.
I am having a hard time with units getting moved on tiles, where a other unit is still present and so on.
Is there some kind of algorithm or even brute-force approach to match the the criteria?

One bug you could encounter is that in a single turn moving up to make space will never increase the total attacks that turn. Since moving up consumes one action it prevents one attack. The ally that moves into the freed space can attack once. The total attacks this turn are unchanged.
You could resolve this in two ways:

looking ahead multiple turns and maximizing attacks using a brute force method (something like min-max) this is doable but of approximate complexity O(  (36p)^n  ) where p=pieces and n=turns that you look ahead.
Decide on a behavior, and write a program to have the pieces move that way. This is less resource intensive, but a bit abstract. It will not give a strategically perfect AI.

Given what you describe I would recommend the second option. The desired behavior is to shuffle up in oder to let an ally advance.
This could be done by evaluating units that are within one tile of the players units. They can mark tiles as desired. Units whose tile is desired by an ally will try to advance and attack instead of attacking twice. If this is not possible they decide to attack twice, and the piece behind them tries to find a different square to move into. Pieces further away will move towards enemies, until they get close enough to start requesting that their allies give them space.


text:
Player jittering against wall when held down button
So, I'm making a top down RPG.
Everything's going excellent, but this problem is quite annoying. Now, when the character moves against the wall, the player jitters back and forth. I'm guessing it's because the player is trying to move into the wall, and then the wall collision is pushing it back, which makes an annoying back and forth movement. My question is obviously, how do I stop this from happening?
Thanks!
PS: I'm using transform.translate to move the player, and I'm using C#.
EDIT: I'm also using a 2D Rigidbody, and 2Dbox colliders on both.

You just need a sweep test before you translate

http://www.gamedev.net/page/resources/_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084

Oh. Uh... I'm not sure how to add this in Unity C#. I'm a little new to C#. If you have the knowledge, would you mind explaining how to implement this?

The jittering is happening because you're warping the player into the wall using Transform.Translate, and the physics step is saying, "Hey, we're in the wall. Let's solve this collision issue and push the player back out of the wall."
To avoid this, when using a Rigidbody2D, it's advisable to use Rigidbody2D.MovePosition. This ensures you won't have overlapping colliders when moving. If a collider and rigidbody can't move because something's in the way, it won't jitter.
Using Rigidbody2D.MovePosition, you may want to set the Rigidbody2D.interpolation value to keep the movement looking smooth.
However, if Rigidbody2D.MovePosition isn't ideal for your game for some reason and you still want to use Transform.Translate, use Physics2D.Raycast (or other Physics2D casts) to see if moving would make you hit a wall or not, and only move if no wall is hit.


text:
Why doesn't Unity keep keydown states between scenes, and how can I change that?
So basically, when my scene in Unity changes and I'm holding down, say, Right or Left, when the scene resets, my player (and Unity) doesn't even recognize that I'm still holding that button, until I lift my finger and put it back.
Any thoughts?
Sorry for any broken English or anything, I'm running off two hours of sleep.

Using this in my dataHolder that  persists between scenes I continuously got space key was pressed logged in the console.
 void Update () {
        if (Input.GetKey("space"))
            print("space key was pressed");
    }

The trick here is to make sure the instance of the script that handles button presses persists between scene loads.

Ah, why didn't I think of that? Thank you!

I'm coming to this very late, but I ran into a similar issue. From what I tested, Unity seems to preserve keystates between scenes unless multiple keys are down, in which case it loses the first key to be pressed when a new scene is loaded. This is actually a super easy fix: Instead of using Input.GetKey(), you can use OnGUI() and use a boolean to detect if a certain key is down. Unity seems to handle this better, and the boolean will be preserved (provided that the script you're using persists). I'm not sure if this was the exact issue you were facing, but this is one way to fix it :)


text:
Another way of writing 2D arrays on Game Maker Studio?
I'm making a map in an array, something like this :
mapa[23,26]=4;mapa[25,28]=3;mapa[21,28]=3;mapa[22,30]=3;mapa[24,30]=0;
mapa[22,27]=5;mapa[23,27]=0;mapa[24,27]=0;
mapa[22,28]=1;mapa[23,28]=0;mapa[24,28]=0;
mapa[22,29]=0;mapa[23,29]=0;mapa[24,29]=0;
mapa[23,33]=0; mapa[23,32]=0; mapa[23,31]=0;mapa[23,30]=0;

This is tedious. In other languages 2d arrays can be written like :
int[][] myArray = {  {0, 1, 2, 3},
                     {3, 2, 1, 0},
                     {3, 5, 6, 1},
                     {3, 8, 3, 4}  };

Can I write in Game Maker Studio 2Darrays like this?

I strongly suggest keeping as many resources/data in files rather than hard-coded/compiled into executable.
For example, the csv format should be suitable for storing data simple as like 2D arrays of integers are and there should not be any problems finding a csv reader for GameMaker or implement csv reader yourself easily(+-20 lines)
mapa.txt:
0, 1, 2, 3
3, 2, 1, 0
3, 5, 6, 1
3, 8, 3, 4
//MUCH cleaner and flexible code
mapa = loadCSV(mapa.txt); //loadCSV not part of gamemaker, need to download/implement


text:
Movement & arriving using forces
3D. Given a point mass m, inital position p0 initial velocity v0, and a desired location d, how do I apply forces (with magnitude no greater then fMax) to move m to d and stop. I know how to apply forces, it's the strategy for determining what force to apply each frame.
You would think this would be easy - but it's turned out to be difficult.
A solution that only converges at the limit is not acceptable (i.e. having the mass oscillate back/forth over the destination by smaller and smaller distance)
Edit: This is not the same as this question. Finding the stopping distance is trivial, but is (maybe) only part of the solution.
Edit: Also not the same as this question, because the highest answer is incorrect (as stated by my constraints)

Does m move in frictionless and gravityless space? Should m reach max speed in between, ie. travel in shortest time, or should m maintain v0 until it's time to start slowing down? If you use a physics engine to handle the mass calculation (do you?), it is unlike that you hit d at nth decimal, since physics engines have internal behaviour that affect (cease) the most tiny movements. This probably doesn't matter?  Also the physics solver may have an internal damping that consumes energy and scrambles the calculation a bit. Is this a simulation of real-world objects and movement?

Are you familiar with the kinematics equations (for movement under constant acceleration) as outlined in my answer here: http://gamedev.stackexchange.com/questions/54732/how-to-implement-deceleration-and-stopping-over-a-certain-distance/54808#54808

@PieterGeerkens yes, I'm fine with the physics. Finding the braking distance is easy - but is only part of an overall strategy.

@Stormwind Doing the physics simulation myself. For now, can assume frictionless and gravityless. Yes, real-world objects and movement - but for now, assuming idealized. Will iterate after.

I assume you also want to minimize the time to reach the target (and/or the total force over time applied)? Otherwise, a trivial solution is to first decelerate the object until it stops at some arbitrary location x, then apply constant force towards d until you reach the halfway point between d and x, and then reverse the force.

What you're describing is a classical controls problem. An old subject and widely studied by most engineering students.
There are two approaches you can take, one that involves tweaking (PID controller) and one that's based on math & control theory.

PID controller: proportional-integral-derivative controller (more on Wikipedia) relies on the difference in your position and the destination (proportional), your total error distance (integral), and the speed (derivative). This video explains it very well. It works by multiplying each input value by a constant factor (called the gains) to obtain a force to apply. So you'd have a function, getControl(), which provides how much force to apply.
def getControl(gains, dist2dest, totalError, speed):
    P, I, D = gains
    control = P*dist2dest + I*totalError + D*speed

Picking values for the gains is called 'tuning' and can be done interactively with your physics model. Once you're satisfied with the behavior, save the values.
Info on how you move (i.e. what is the position as a function of force?) is required to solve this with maths.

Root Locus (more on Wikipedia). Once you have a transfer function, G (function that describes your system dynamics --> pos/force = G(s), in Laplace-space), you can plot the root locus (matlab fxn 'rlocus') to visualize the dynamics and add controller zeros/poles automatically (matlab fxn 'place') or by hand to place the closed-loop poles where you want in order to obtain desired behavior (no overshoots, short transient time, etc.)

Force can be constrained by simply setting any force greater than fMax to fMax.

Yes. Use a PID controller, it will handle the initial velocity, and even overcome varying friction. I wrote a primer http://ps3computing.blogspot.ca/2013/03/proportional-integral-differential.html


text:
Behaviour tree editor Unity
I'm a programmer, so I am perfectly aware of how to implement a behaviour tree. I don't want to rely on third party tools, but still have convenient tools for creating the AI for my game.
I was looking at tools like this one but I could not find out how to create editor extensions like that in Unity.
I also noticed that there is a new experimental feature (Playables) in the current versions of Unity.Does this use the state machine editor from the Animator? Should/Could I use that to implement a behaviour tree?

The general topic you're interested in is editor scripting.
Here's Unity's start page for it:
http://docs.unity3d.com/Manual/ExtendingTheEditor.html
Here's a tutorial they put together as well:
https://unity3d.com/learn/tutorials/topics/scripting/editor-scripting-intro
Neither of those links deal directly with making a node based editor, which is likely what you want to do.  I recommend you check them out though, as they'll give you some basics on extending the editor in general, which you'll need as a starting point.
Once you're familiar with the basics of editor scripting, you may find this useful:
http://forum.unity3d.com/threads/simple-node-editor.189230/


text:
Get relative angle to collision Unity
I want to get the angle between the rotation (euler Angles) of the camera (V1 : Vector3) and the collision point of my character, when it hits a wall, to determin, if it was left, right, or in front of it.I tried to use Vector2.Angle with V1 and V2 (ControllerColliderHit.moveDirection as a Vector2) to get the difference between them.
However I get a different value (0, 90, 180) when running into the wall depending on the world direction. (left wall, right wall, etc.)
How can I get the angle of the collision point relative to the direction the camera is facing?

What vector are you using to represent the camera's forward vector in Vector2.Angle?

It's orientation (transform.rotation)


text:
How to convert -1 to 1 coordinate back to screen coordinates?
Here is a question in which Questioner asks how to convert world coordinates to 1 to -1 coordinates like Opengl, I want to know how to do that in reverse, that given a coordinates between 1 and -1 (both x and y axis), how can i change it back to screen coordinates. i.e if my width and height is 1000, and given a coordinate (0,0), how can i change it to 500, 500, So that i can render it.

For this problem specifically:
screenX = ((glX + 1) / 2.0) * maxScreenX;
screenY = ((glY + 1) / 2.0) * maxScreenY;

In general, the solution for going from coordinate system A to coordinate system B is:
$$
B = \frac{A - min_A}{max_A - min_A}  (max_B - min_B) + min_B
$$
or as pseudocode:
B = ((A - minA) / (maxA - minA)) * (maxB - minB) + minB;

For example substituting into your example with \$B\$ representing screenX and \$A\$ representing glX, we'd get:
$$
\begin{align}
\text{screenX} &= \frac{\text{glX} - \text{minGlX}}    {\text{maxGlX} - \text{minGlX}}
(\text{maxScreenX} - \text{minScreenX}) + \text{minScreenX} \\
\text{screenX} &= \frac{\text{glX} - -1}{1 - -1}(1000 - 0) + 0 \\
\text{screenX} &= \frac{\text{glX} + 1}{2}1000
\end{align}
$$
or as pseudocode:
screenX = ((glX - minGlX) / (maxGlX - minGlX)) * (maxScreenX - minScreenX) + minScreenX;
screenX = ((glX - -1) / (1 - -1)) * (1000 - 0) + 0;
screenX = ((glX + 1) / 2) * 1000;

Do you mean B(x, y) by B and A(x, y) by A ?

Sort of, but the min & max apply to each coordinate component separately. I've added an example showing how to substitute the coords in.