text:
Best collision algorithm for Axis Aligned Bouding Boxes
I have a number of quads (suppose like 20-40) and i want to quickly check the collisions between any of them. I would like to know if there's a quick algorithm to do that 60 times per second without performance decrease

Regarding my close vote:  your answer lays firmly within the "collision detection" section of the accepted answer to that question.  Spoiler:  the answer is space partitioning.

Oh i didn't see the duplicate, thanks for that by the way.

You may want to consider looking to spacial partitioning, such as a Quadtree.
In a nutshell, you would be dividing your world into sub-sections, and only check collisions between objects that are inside of the same sub-sections, greatly improving the complexity.

In the worst case (for 40 AABBs) you'll need to do 780 tests. There's not going to be any problems with a simple 4 comparison test:
a_min.x <= b_max.x
b_min.x <= a_max.x
a_min.y <= b_max.y
b_min.y <= a_max.y

If all of these are true, you have an intersection.
At this point partition structures (like AABB trees) are not necessary at all. You might only want to start thinking about them when test count goes over 10 000, which is when you need to test about >140 AABBs.
Best to avoid using the broadphase for as long as you can because it will introduce a lot of complexity and hard choices and measurements. Not one of them is going to give a good speed improvement without serious workload and staying within special constraints with your AABBs.

So you're claiming that a simple collision test between two bodies will overwhelm having an O(n^2) algorithm for the number of tests?  I disagree.

@SethBattin I'm not sure what you think I'm saying. And what "bodies"? To my understanding, we're talking about AABBs here.

I'm saying that recommending against a broadphase because each individual test is simple is bad advice.  Your performance threshold numbers are going to be completely technology- and system- dependent; they aren't good rules of thumb.  And you're conflating bounding boxes of bodies with the structure that holds them (a tree), which doesn't make sense either.

@SethBattin A low-end 1 GHz CPU on Android can easily crunch at least 100k hash table reads per second, you think 3200 two-instruction cache-efficient comparisons can slow anything down? No need to assume ridiculous things. Any tech this wouldn't work on was discontinued at least 10 years ago. As for "conflating" - you seem to be imagining things now. a) Nobody except you is talking about "bodies". b) OP wants to compare AABBs. c) At no point did I say that AABBs have to be integrated in AABB trees. P.S. BVHs have overhead, you know. It's not like they magically speed things up for free.

A nice but lesser well known algorithm for this situation is called dimensional reduction.
If you keep your list of rectangles sorted on one axis (say, x axis by sorting on the minimum x value of the rectangles), then collision detection just becomes a 1 dimensional overlap test on the y axis, for whatever overlaps there were on the x axis.
Works better when most objects are stationary, but the same is true of all spatial subdivision algorithms (;


text:
How do I render a PNG image with OpenGL?
I have an image (100×200 px) painted with Paint.NET and saved as a .png with 32-bit color depth. How can I render it using OpenGL 1.1  (with the LWJGL binding) or higher inside the display?
I tried creating a ByteBuffer, then loading the pixel color values inside that buffer, but I'm missing the OpenGL settings that need to be enabled. Some help?

As far as I know, you can't render a 100200 image. Try 128256 instead.

So you mean only base 2 resolutions?

@BlackHamm3rJack They're called power-of-two textures. But they also must be squared, 128x256 is not squared. The common resolutions are 2x2, 4x4, 16x16, 32x32, 64x64, 128x128, 256x256, 512x512, 1024x1024, and 2048x2048. Not all graphics devices support larger resolutions, though.

Forgot to mention, some graphics devices support non-power-of-two textures. Some convert to power-of-two at run-time. It's just that some don't support them at all.

But why just power of two textures? What differs?

Because not all devices support it. I've never had a problem with my computer drawing oddly-shaped textures, but some do. If you're making a game and want to support a wider range of computers, use power-of-two textures and simply only draw the part of the texture you want. You can also use non-power-of-two assets, then have your engine add a border to make it power-of-two and draw only the parts that were of the original texture.

Okay, btw my textures are all power of two. That 100x200 was just a test

@BlackHamm3rJack Modern Gpus are able to use resolutions like 128*256. Some don't.

First, this question is about asking for a tutorial, and as far as i know googling "opengl tutorial" is enough to get you started.
Second, i don't recommend you to use such an old version of opengl, even if you want to support an extremely large range of computers, the 'modern opengl' (a.k.a. Opengl 3.0+) is widely supperted as well.
And imho learning opengl 1 is useless for any intermediate complexity project, because it lacks of many essential features (see framebuffer objects).
That said, if you give up with gl1, non power of two textures will be fully supperted on every machine.
Here I want to give you a fair starting point to solve your actual problem (this is not for lwjgl, though, and I assume gl3+ with shaders):
In opengl you don't render textures, you render geometry, so you have to draw a quad with the proportions of your textures.
To do this, feed a buffer with the data of this specific geometry and draw it.
Now it's time of shaders, you will need a vertex and a fragment shader, where you actually sample a texture object created before to output your quad filled with your texture.
Now, you are aware that with only what i wrote, you can't do anything, because all the details that you need to write a working program are missing, so
http://bfy.tw/qKL

I was using OpenGL 1.1 just because LWJGL tutorials used that, not because i need to support a wide range of systems. By the way... I'll start woth modern OpenGL so...

That's your best option, and btw I started with lwjgl too, and in their docs there are some insights for gl3 :)

I wouldnt learn legacy GL ever, if you dont want to learn modern GL use a wrapper library.

"Rendering is the process of generating an image from a 2D or 3D model"-wiki  Textures are part of that process, "rendering a texture" isnt an invalid thing to say.

Well, a texture isn't a model, so I wouldn't say "render a texture", but this is not the point of the question

source: Stack Exchange

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

sort: votes


text:
Is Update called based on screens refresh rate? MonoGame
My game is running 60fps (Because I'm using a 60hz monitor) but if I would use a 85hz monitor it would be running 85fps. My question is if update is called based on the screens refresh rate or if its limited to 60 calls per second

Some 60Hz monitors have an option in the settings to drop down to 30Hz. If you have that option, you could at least see if it actually drops downwards to 30fps.

Yeah that sounds like a good idea Shiro

Unfortunatly I just found out I can't do that with my monitor :|

Why does it matter?

It's not matter if you're using deltaTime based calculations.

it matters because if I do 60 * deltaTime on a 85hz monitor the result will be 0.7058823528 and that will look choppy right (if I don't use antialiasing and point filtering)

If you are moving objects by using constant * deltaTime, your movement will have the same speed for all frame rates

I know shiro.. but it will look choppy wright because I'm moving 0.7058823528 pixels every frame

But this has nothing with the question to do.. Is Update called based on screens refresh rate?

I know. It has to do with your previous comment. It definitely won't "be choppy"

As far as I know, the fixed timestep in Monogame is 60 per seconds, regardless of the monitor refresh rate. The statement "it runs 85fps because my monitor refresh rate it 85hz" is false.
It just tries to give you 60 updates per second. It cannot guarantee it does, therefore using logic based on elapsed gametime is the best way to go.
If you want another timestep than 60, change the property TargetElapsedTime to the desired value. Again, this is unrelated to the refresh rate of your monitor since you can set the value yourself.
Read this http://blogs.msdn.com/b/shawnhar/archive/2007/07/25/understanding-gametime.aspx for more information on how it is implemented in XNA (Monogame is based on this).

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


text:
Does fixed time step deltaTime get higher if the computer can't handle it?
If you use fixed time step and set it to for example 0.0166667 does it ever go up if the computer can't handle 60 updates/ticks per second?

The answer is basically no, most fixed timesteps don't adjust the timestep if they cant keep up.
The actual solution to this problem used depends on the needs of your game and the reasons that it can't keep up.
If the reason that it can't keep up is rendering on the GPU, that means that the CPU is able to do more work even though the GPU isn't.  In this case, you may opt to have your game run multiple simulations for each render, to keep the simulation caught up to real time.
Note that if your game goes a lot faster than your fixed update time, you may also opt to do multiple renders between simulation updates, and maybe do a linear interpolation between last and next simulation datas to make a smoother looking simulation.
If it really just unable to keep up at all, often games will be ok with not keeping up with real time and just letting the game run more slowly, but keeping the time step the same.
The reason most fixed timestep games don't adjust time steps when they run too slowly is that adjusting the time step at all ever makes you lose whatever benefits of fixed time steps that made you decide to use them - like deterministic simulation, or consistent physics behaviors.


text:
sfml/opengl, two objects of same class are sharing variables
whenever I use the none-default constructor, it only adds to the coordinates of the previous class(in an array)
wall_1x1 wall[2] = {
    wall_1x1(0, -2, 0), //first argument is x, second z, and third ry
    wall_1x1(1, -2, 0)
};

the second object in the array will be behind the first object(by -2 z) and if I give the first object an ry of 90, all the other objects will have the same rotation.
#pragma once
#ifndef WALL_1X1_H

#include <GL\glew.h>
#include <SFML\Graphics.hpp>

class wall_1x1 {

public:
  wall_1x1();
  wall_1x1(float x, float z, float ry);
  ~wall_1x1();
  void up();

private:
  float m_x;
  float m_z;
  float m_ry;
  GLuint tex;
  sf::Image data;
};

#endif

and the .cpp class:
#include "wall_1x1.h"

GLfloat verts[] = {
  0, 0, 0,
  1, 0, 0,
  1, 1, 0,
  0, 1, 0
};

GLfloat coords[] = {
  0, 0,
  2, 0,
  2, 2,
  0, 2
};

wall_1x1::wall_1x1() {
  m_ry = 0;
  m_x = 0;
  m_z = 0;
}

wall_1x1::wall_1x1(float x, float z, float ry) {
  m_ry = 0;
  m_x = 0;
  m_z = 0;

  m_x = x;
  m_z = z;
  m_ry = ry;

  data.loadFromFile("wall1.png");

  glGenTextures(1, &tex);
  glBindTexture(GL_TEXTURE_2D, tex);
  glTexImage2D(
    GL_TEXTURE_2D,
    0,
    GL_RGBA,
    data.getSize().x,
    data.getSize().y,
    0,
    GL_RGBA,
    GL_UNSIGNED_BYTE,
    data.getPixelsPtr());
}

wall_1x1::~wall_1x1() {
}

void wall_1x1::up() {
  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  glVertexPointer(3, GL_FLOAT, 0, verts);
  glTexCoordPointer(2, GL_FLOAT, 0, coords);
  glBindTexture(GL_TEXTURE_2D, tex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTranslatef(m_x, 0, m_z);
  glRotatef(m_ry, 0, 1, 0);
  glDrawArrays(GL_QUADS, 0, 4);
  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}

and the important parts in main:
wall_1x1 wall[2] = {
    wall_1x1(0, -2, 0),
    wall_1x1(1, -2, 0)
};
....

wall[0].up();
wall[1].up();

You can see the value of your member variables in your debugger, and it will show you the correct values.
Your problem lies in that the matrix transformation commands of legacy OpenGL are accumulating on top of each other.
If you want to start from a known state, you need to look into the functions that let you load an identity matrix, push and pop on the matrix stacks, and load/store matrices.

Now I feel dumb, like you said I forgot to add "glPushMatrix" and "glPopMatrix" but thanks!


text:
libGDX: Why doesn't Gdx.input.isKeyJustPressed() work?
I'm trying to use the method Gdx.input.isKeyJustPressed() to check if the Android BACK button was just pressed. I don't want to use the Gdx.input.isKeyPressed method to avoid multiple calls. Here is my code:
public void handleInput() {
    if(Gdx.input.isKeyJustPressed(Input.Keys.BACK)) {
         // show previous screen...
    }
}

public void update(float dt) {
    handleInput();
}

But unfortunately this doesn't work. Any ideas?

This does work. Put a breakpoint inside handleInput() and see if the code is even reached, it's probably not and your missing a call to it somewhere deeper down the line.

@MennoGouw If I replace isKeyJustPressed() with isKeyPressed() it's working. The problem seems to be with the isKeyJustPressed() method.

Below code works for me, I get the message when pressing the back button.
if (Gdx.input.isKeyJustPressed(Input.Keys.BACK))
        {
            Gdx.app.log("Debug", "Back pressed!");
        }

Are you calling below method before the one above?
    Gdx.input.setCatchBackKey(true);

I also called the setCatchBackKey(true). But it it doesn't work. I'm going to use the isKeyPressed() method and prevent multiple calls by saving the last key state and make only a call when the last key state is different from the current.


text:
What's the difference between the representation of a line and that of a line segment?
What is the difference between a line and a line segment from the implementation point of view?
To me, line segment means:
class LineSegment2d
{
Point2d start, end;
public:
    ......
}

This representation should be enough to represent a line for any practical purpose in CG. But how do we describe a line and distinguish it from a line-segment?

I'm voting to close this question as off-topic because it's not about game development.

If this is not related to game programming then I can argue that any linear algebra or geometry questions are not related to gamedev...

Technically, a line has no beginning or end. It is infinite in length. For disambiguation, this is often called a ray in graphics programming. A line of this type is described by any point on the line plus a direction.
A line segment is what most people are referring to when they say 'a line'. It has a beginning and an end point. It's common to refer to a line segment simply as a line, since we don't normally deal with lines of infinite length.
Computationally, they are identical. While it's possible to represent an infinite line with only an origin and a direction of arbitrary length, it's impossible to perform calculations on infinities so lines are generally handled the same as line segments, either as two points or as an origin plus a vector (direction with length). It's basically free to store an implicit working length in the direction vector anyway. The only difference is in the inherent meaning. A line segment connects two points, whereas a line or ray passes through two points.
pseudo-code:
// 1. defined with {point, point}
lineRay = {{1,2} , {2,3}}
lineSegment = {{1,2} , {2,3}}

// 2. defined with {origin, vector}
lineRay = {{1,2} , {1,1}}
lineSegment = {{1,2} , {1,1}}

Here, the lineRay and lineSegment are identical in both definitions. The only difference between the lineRay and lineSegment is in the implied meaning of the points. The difference between the two methods of definition is strategic, depending on how the lines will be used. Graphics are represented with points whereas calculations are generally performed using the vector format. They are also easily converted between by adding or subtracting the origin point.
If for example, you were calculating the intersection of two (non-parallel) unbounded lines (rays) you would simply find the intersection point and return it. If one or both lines are bounded (line segments), you would find the intersection point, then you would perform extra checks to determine if the point falls within the bounds of the segment.
The first method could also be thought of as two vectors where the origin is at {0,0}.

It's hard to tell what exactly you are looking for but line segments are commonly described by their endpoints, or by a point, a normalized direction vector and a length.  Another way would be a starting point and a non normalized direction vector which also is the length.
For the purposes of raytracing, I usually use that second form (starting point, normalized direction and length).
The third form could be good if you wanted to work in a parameterized 0 to 1 value "time t".  You multiply your time t value by the direction vector and add it to the starting point. This would be useful for moving something from one point to another over time.
Lines can also be described by two points on the line, or by a single point and a direction vector that may or may not be normalized.
There are also of course other ways to describe a line mathematically, but these are the ways I've seen most often in game development.
Does that help at all? If not lemme know, I might have better info for you.


text:
What's wrong with my HLSL depth shader?
I'm trying to render depth texture in XNA 4.0. I'm read few different tutorials several times and realy cannot understand what I'm doing wrong.
Depth shader:
float4x4 WVPMatrix;

struct VertexShaderOutput
{
    float4 Position : position0;
    float Depth : texcoord0;
};

VertexShaderOutput VertexShader1(float4 pPosition : position0)
{
    VertexShaderOutput output;
    output.Position = mul(pPosition, WVPMatrix);
    output.Depth.x = 1 - (output.Position.z / output.Position.w);
    return output;
}

float4 PixelShader1(VertexShaderOutput pOutput) : color0
{
    return float4(pOutput.Depth.x, 0, 0, 1);
}

technique Technique1
{
    pass Pass1
    {
        AlphaBlendEnable = false;
        ZEnable = true;
        ZWriteEnable = true;

        VertexShader = compile vs_2_0 VertexShader1();
        PixelShader = compile ps_2_0 PixelShader1();
    }
}

Drawing:
this.depthRenderTarget = new RenderTarget2D(
    this.graphicsDevice,
    this.graphicsDevice.PresentationParameters.BackBufferWidth,
    this.graphicsDevice.PresentationParameters.BackBufferHeight);

...

public void Draw(GameTime pGameTime, Camera pCamera, Effect pDepthEffect, Effect pOpaqueEffect, Effect pNotOpaqueEffect)
{
    this.graphicsDevice.SetRenderTarget(this.depthRenderTarget);
    this.graphicsDevice.Clear(Color.CornflowerBlue);
    this.DrawChunksDepth(pGameTime, pCamera, pDepthEffect);

    this.graphicsDevice.SetRenderTarget(null);
    this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp, null, null);
    this.spriteBatch.Draw(this.depthRenderTarget, Vector2.Zero, Color.White);
    this.spriteBatch.End();
}

private void DrawChunksDepth(GameTime pGameTime, Camera pCamera, Effect pDepthEffect)
{
    // ...

    this.graphicsDevice.RasterizerState = RasterizerState.CullClockwise;
    this.graphicsDevice.DepthStencilState = DepthStencilState.Default;

    // draw mesh with pDepthEffect
}

Result:

As I see output.Position.z always equals output.Position.w, but why?

If you work out your matrix math, you'll see that the resulting w component of a vector/matrix multiplication depends on what's in the 4th column of the matrix. If the last column is [0 0 0 1] (which it typically is for most translation/orientation matrices), then the w component will be whatever the w component of the vector was. However for a typical perspective projection matrix, the last column will be [0 0 1 0]. This means it will be equal to the z component of the vector, which in this case means that w will be the view-space z value of the vertex position.

This means that if you are using a typical projection matrix, position.z = position.w. Instead maybe you could try passing the maximum Draw Distance of the current camera to the shader and divide position.z by that. That way you'll get a smooth transition from closer to further depth.

Yeah, I thought so that just need to pass the distance. But could not figure why this process is described in all the examples, and why it does not work in this case? Anyway, thanks for the explanation. Matrix is not my forte.


text:
How heavy is a scene load in Unity assuming all referenced objects are in memory?
From what I understand, resources that are local to a particular scene( not a prefab, or texture, material asset etc ) are embedded in the scene file itself, while external resources are just referenced and loaded if needed. The game I'm working on requires all scene be loaded from an asset bundle. Which means by the time the level is loaded, all data should be in memory.
In order to show relatively accurate load progress, I sum of the total bytes of all the needed asset bundles to load the level and divide that by the (approximate) number of bytes loaded so far( calculated using the file size of the asset bundle in bytes multiplied by Unity's AssetBundleRequest.progress value ).
However, this isn't possible with Application.LoadLevel since there's no way to weigh how long it might take relative to the time it took to load the asset bundles.
So, my question is, does Application.LoadLevel take long enough to be an issue if ignored? The presence of an async version of this method leads me to believe there is some need for this. That might only apply for scenes that were built into the game rather than into an asset bundle though.

you can use load async and check the progress of the AsyncOperation returned, can't you?

Which returns a value between 0 and 1. If I want the scene load progress to count towards the current loading bar, I need to convert that to a value relative to the rest of the loading tasks. I'm trying to show the progress in one loading bar, basically.


text:
How to rotate a whole rectangle by an arbitrary angle around the origin using a transformation matrix?
Suppose, I have a rectangle ABCD. Where, A(0,0), B(7,0), C(7,5) and D(0,5).
I want to rotate the whole rectangle by theta = 50°.

I know that, a rotation transformation matrix can be used to do that.

So, I have done the following:
A' = [0   0   1] ;     B' = [7   0   1] ;
C' = [7   5   1] ;     D' = [0   5   1] ;
But the output has become skewed:

What should be the correct calculation?

Your maths looks right.

@immibis, no my math is wrong! I discovered that. see my answer. I am feeling like heavens!

I have solved the problem.

//Roation around the Origin
//Individual matrices

#include "graphics.h"
#include "Vector2d.h"
#include "Coordinates2d.h"
#include "Polygon2d.h"
#include <math.h>
#include <iostream>

#define PI 3.141
#define DEG 45.00f
#define RAD 6.283185308 / (360.0 / DEG)

int main()
{
    ////////////////////////////////////////
    Coordinates2d::ShowWindow("Roation around the origin(individual matrices)");
    ////////////////////////////////////////

    Matrix a(1,3);
    a.SetItem(0,0,0);   a.SetItem(0,1,0);   a.SetItem(0,2,0);
    a.Show();

    Matrix b(1,3);
    b.SetItem(0,0,140); b.SetItem(0,1,0);   b.SetItem(0,2,0);
    b.Show();

    Matrix c(1,3);
    c.SetItem(0,0,140); c.SetItem(0,1,100); c.SetItem(0,2,0);
    c.Show();

    Matrix d(1,3);
    d.SetItem(0,0,0);   d.SetItem(0,1,100); d.SetItem(0,2,0);
    d.Show();

    Matrix rot(3,3);
    rot.SetItem(0,0,cos(RAD));  rot.SetItem(0,1,sin(RAD));  rot.SetItem(0,2,0);
    rot.SetItem(1,0,-sin(RAD)); rot.SetItem(1,1,cos(RAD));  rot.SetItem(1,2,0);
    rot.SetItem(2,0,0);         rot.SetItem(2,1,0);         rot.SetItem(2,2,1);
    rot.Show();

    Matrix ma;
    ma = a.Multiply(rot);
    ma.Show();

    Matrix mb;
    mb = b.Multiply(rot);
    mb.Show();

    Matrix mc;
    mc = c.Multiply(rot);
    mc.Show();

    Matrix md;
    md = d.Multiply(rot);
    md.Show();

    Polygon2d poly;
    poly.Add(0, 0);
    poly.Add(140, 0);
    poly.Add(140, 100);
    poly.Add(0, 100);
    Coordinates2d::Draw(poly, Yellow);

    Polygon2d poly2;
    poly2.Add(ma.GetItem(0,0), ma.GetItem(0,1));
    poly2.Add(mb.GetItem(0,0), mb.GetItem(0,1));
    poly2.Add(mc.GetItem(0,0), mc.GetItem(0,1));
    poly2.Add(md.GetItem(0,0), md.GetItem(0,1));

    Coordinates2d::Draw(poly2, LightGreen);
    ////////////////////////////////////////
    Coordinates2d::Wait();
    ////////////////////////////////////////
}

What did you change?

@immibis,  [x   y   1] is changed to [x   y   0].

Exerpt from the 3D CSG module I wrote for my engine.  You should be able to derive from this easily enough.
SOLID_C *Rotate(const V3 &axis,const T angle)
{
    T a=radians(angle),c=cos(a),s=sin(a);
    V3 rt[3],m[3],mt[3],ax=((V3)axis).normalise(),t=ax*(1.-c);
    rt[0][0]=c+t[0]*ax[0]; rt[0][1]=0+t[0]*ax[1]+s*ax[2]; rt[0][2]=0+t[0]*ax[2]-s*ax[1];
    rt[1][0]=0+t[1]*ax[0]-s*ax[2]; rt[1][1]=c+t[1]*ax[1]; rt[1][2]=0+t[1]*ax[2]+s*ax[0];
    rt[2][0]=0+t[2]*ax[0]+s*ax[1]; rt[2][1]=0+t[2]*ax[1]-s*ax[0]; rt[2][2]=c+t[2]*ax[2];
    m[0].set(1,0,0); m[1].set(0,1,0); m[2].set(0,0,1);
    mt[0]=m[0]*rt[0][0]+m[1]*rt[0][1]+m[2]*rt[0][2]; mt[1]=m[0]*rt[1][0]+m[1]*rt[1][1]+m[2]*rt[1][2]; mt[2]=m[0]*rt[2][0]+m[1]*rt[2][1]+m[2]*rt[2][2];
    M3 mat(mt[0],mt[1],mt[2]);
    return Apply(mat);
}

SOLID_C *Apply(const M3 &mat)
{
    FACE *f; V3 t; UINT i=(UINT)vl.size(); while (i--) t=vl[i],vl[i]=mat*t;
    i=(UINT)fl.size(); while (i--) f=fl[i],t=f->nrm,f->nrm=mat*t,f->dist=f->nrm.dot(vl[f->vl[0]]);
    return this;
}

I have just solved it by myself. I have also posted the code.

Yeah, I noticed that after I posted mine. Should I delete mine then? (New to SE, sorry for noobness.)

No need to delete. No problem. I can up vote you.

Ohh, thanks. I guess it's a case of 'same problem, multiple solutions' for others then. Always nice.

Most of trigonometric functions take radians as input, this may be your issue.
So your theta should be
float theta = angleInDegrees*PI/180

No. That was not the issue. I used that.

If that was the problem it would still be a rotation, just not by the right angle. It wouldn't be skewed.


text:
How should asset bundles be divided?
The only way to load an asset from an asset bundle into memory is to load the entire thing, decompress and pull out the asset you want, then unload the entire thing, except the assets you want. This seems impractical for sharing assets between bundles. For example, if asset bundle A wants a single asset from asset bundle B, it must load all of B, pull out the asset, then destroy B. The alternative to this is to extract the shared assets and create a new bundle call asset bundle C. The problem with this is that B must have been designed this way before being built, which it won't be if it was built before A (it has to be since A depends on B).
Using the resources folder results in a huge blob of bytes that, from what I understand, cannot be changed after build, and is certainly not differ able for patches.
Putting the pros of asset bundles and the resource folder together, I figure that having an asset bundle for every asset is the best of both worlds. Is there problems with this? Is my understanding of asset bundles or the resource folder flawed?

You are correct in your assumptions. For our project we have an editor script which runs through all our assets, packs some of them into small bundles and saves information about each bundle into config. When we need to load something at runtime our system determines whether it should fetch data from Resources or asset bundles. This way we can adjust our build size and memory footprint. The hard part with this approach is to correctly unload bundles after you are done with them, otherwise you can end up with memory leaks or black textures. Also keep in mind that loading a bunch of small bundles is way slower than loading one big bundle, it can significantly hurt user experience.


text:
How animated block in voxel engine?
In my voxel engine (XNA 4.0) I'm use a vertex buffer for the entire chunk and update it after the set block, changing block metadata or light level. This is not too frequent operation compared with the time of mesh rebuild. But now I want animate some blocks, for example, make door opening or lever switching smooth.
If I remember right, in Minecraft all draw on the fly using OpenGL (correct if wrong), but in my case this is not an option.
I'm know what is a bone animation and how it works, and I think that I can make something like this for animatable block X:

rebuild chunk mesh without animated part of block X;
create entity looking like removed animated part and animate it;
remove entity and rebuild chunk mesh with that part in another static position.

I'm not shure this is a correct way. Any better ideas?
Also, how to make a block with animated textures? Do I need to use for this purpose a separate shader or I can somehow a correct texture coordinates of vertices in existed meshe?
Thanks.

It's a good idea to keep your static terrain in a single buffer. Updating it for small changes is totally reasonable. However for something like an animation I think you're going to need to diversify your terrain system. Objects like doors, levers, and other objects that need to be animated should not be drawn with the same buffer as the terrain buffer. You're going to have to re-update a lot of data that hasn't changed every frame of the animation.
I think it's more reasonable to keep these animated objects as separate objects in your scene that are disconnected from the terrain. When you load your terrain from a file when you come across a door that you should draw, don't store that door block as a piece of your terrain, keep it as a separate block that has distinct logic and its own model matrix.
Some animated objects like blocks of water or lava could actually just be "animated" by using a fancy shader effect. Likewise other lighting effects could actually be handled by a shader (research physically based shading and hardware lighting).


text:
accelerometer not working unity
why is the cube moving when I use a controller, but not with the accelerometer?
void Update () {
    text.text = "X: " + Input.acceleration.x + "; Z: " + Input.acceleration.z;
    //transform.position = new Vector3(10* Input.acceleration.y, 0, 10* Input.acceleration.z);

    transform.Translate(Input.acceleration.x, 0, Input.acceleration.z);

    //transform.position = new Vector3(10* Input.GetAxis("Horizontal"), 0, 10* Input.GetAxis("Vertical"));

    transform.Translate(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
}

(I'm on a Xperia Z3 compact by the way)

I guess you might need to apply some speed so that it works on the phone.
Might be the Input.acceleration.x value is not high enough on phone, but works on the controller.
Also it is advisable to use Time.deltaTime to keep the speed constant on all device, else it will change as per the device processing power.
 public float speed = 10.0f;
 void Update ()
 {
        transform.Translate(Input.acceleration.x*speed*Time.deltaTime, 0, Input.acceleration.z*speed*Time.deltaTime);

 }

Suddenly it works for some reason O.o (without modification) - what about "transform.position = 'vector3 from accelerometer'" though?

That will not move it beyond a particular distance as the values from accelerometer will reach a threshold. Try using += on individual axis so that it moves.

I wanted it to not move further than a particular threshhold, so the position mirrored the orientation of the device.
Like when Input.accelerometer.x is at 0.7 the transform.position.x should be 0.7 * 10


text:
How to do offline notifications for Android in Unity3d
I am making a game for Android with Unity3d.
I've been looking for a solution to this on the web for a little, but I couldn't find anything suitable:
I want to make my game have offline notifications.Like...I want to set up an alarm that notifies the user at some point in the future e.g.

"Building complete!"

but the app should not have to be running.
How do I accomplish that?

NEW !! unity added support for mobile offline notifications,
please check here :
https://docs.unity3d.com/Packages/com.unity.mobile.notifications@1.0/manual/index.html

Short answer: You need to create Unity Android plugin of Android project using Google Cloud Messaging.
Details of how to create Android Unity plugin you can find Unity's official site.
Here are some details:
A) You have to start with google Android sample app, understand the push-related API methods
https://developers.google.com/cloud-messaging/android/start
B)You will need API KEY, SECRET
and ANDROID SENDER ID: Project Number assigned when setting up Google Cloud Messaging.
C) Your AndroidManifest.xml. Google Cloud Messaging has some minimum API level requirements for development and testing. Set minSdkVersion property appropriately.
D) Add the following new permissions after the existing element, replacing your_package_namewith the name of the app package for your project. To check the current name of your package go to File > Build Settings > Player Settings and select the Android tab. You will find it in the Bundle Identifier field.
    <permission android:name="**your_package_name**.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="**your_package_name**.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

E) Add the following code after the main activity inside your application tag, replacing it with the name of the app package for your project:
     <activity android:name="com.gamedonia.pushnotifications.GamedoniaPushHandlerActivity" />
     <receiver android:name="com.gamedonia.pushnotifications.PushBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
     <intent-filter>
     <action android:name="com.google.android.c2dm.intent.RECEIVE" />
     <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
     <category android:name="**your_package_name**" />
     </intent-filter>
     </receiver>

F) Use your unity functions to call methods written in your Android project, You can send push notifications from a server scripts.

Thank you for the detailed answer, but I only wanted to use offline notifications.  I heared you can create services for android that run in the background, even when the app is not running.  Is that possible with unity3d?

Yes its possible, Push notification by Android's Google Cloud Messaging (GCM) requires a server as well as online connectivity. What you want to do seems to be something different, called local notification:
You need to look in to this open source project "Unity3D Plugin for Android local notifications with example project" https://github.com/Agasper/unity-android-notifications
Or if you have 15$ you can get this
https://www.assetstore.unity3d.com/en/#!/content/9484

Thank you very much! Seems very helpfull, I'll give it a try! :D


text:
How can shader code duplication be reduced in Unity?
In our current Unity project we have a few shaders that are basically just supersets of another shader. For example, we have a shader that performs lighting calculates with diffuse, normal, specular, and gloss maps, and a shader that performs lighting calculations with a diffuse, normal, specular, gloss, and glow map. The first is a subset of the second, but for performance reasons we've decided to separate them. This leaves us with heaps of duplicated code.
On top of this, I need to add stencil buffer operations to some of these materials, which is about 3 lines, but from what I can see, requires the entire shader file to be copied again.
How can we reduce this code duplication? In an object orientated language we'd used inheritence and polymorphism. What can we do here?

You can use #include files in your shader source files, this is described here.
So like this you can regroup any common code into functions, which you put in an include file.


text:
How can I show slow motion?
In my very, very simple 2D game I'm working on, I'd like there to be moments of slo-mo.
What is the best method of showing the player that the game is currently in slow-motion? As in, what is the most typical and obvious method used by most current games where slow-motion is a feature?
I'm fairly new to game development, and even newer to this site, so am looking for an answer which contains, basically, just bullets of things which should be different between real-time and slow-motion-time.
"Best," to avoid opinionated answers, means established and recognized, common methods of demonstrating slow-mo.

Check this answer for libGDX library. Basically they just multiply the delta factor for some fraction (the delta is the amount of time that has passed between loops)...

Music
Unsurprisingly, slowing down the music currently playing will immediately let the player know the game has slowed down. Alternatively, you can play completely different music to indicate a change in the game's pace, or even play no music at all.
A common way to complement changes in music is to play a transition sound to ease into it rather than change soundtracks on a dime. Imagine something like one of these sounds. (Maybe itself even played at a slower or slowing speed.)
Sound Effects
Most likely you'll want to slow these down as well. Also consider adding reverb if you want some sounds to linger for longer.
Motion Blur
As mentioned in another answer, motion blur can be effective to show slowdown stylishly. But be weary of applying it to every moving object. If the screen is busy, this would create more noise, which may or may not be what you're looking for. Seen here, GTA V only applies motion blur to the car's tail lights.
Screen Filters
As also seen from GTA V, slow motion is accompanied by a changing of the tone of the game's colors. Desaturating the colors creates a more mellow vibe that complements a slow-down.
View Focus
This is more game dependent, but if you're slowing down the game so the player can more easily accomplish a task that requires careful maneuvering, consider zooming in to the area where the player needs to focus. Viewtiful Joe is an example of a modest application of zoom, but the effect is notable.
GTA V doesn't change the camera view at all, but it does add a vignette effect which focuses the player on the car by fading out the screen's edges.

Thank you! This is pretty much a perfect answer. I hadn't even thought of motion blur, or changing music :)


text:
Export normal map from unity?
In unity I can create a normal map out of a black and white image (By changing the type to normal map and select create from grayscale) Im wondering if there is a way to export the normal map like it should look so I don't need to create it from grayscale when I use it in another project?

There is a script available to get this job done. You can follow the instructions specified in the link given below :)
ExportNormalmap
Or else you can check this online tool to get normal maps from images
http://cpetry.github.io/NormalMap-Online/

That exports it more like a height map than a normal map is just grey and white

Is there any other program than unity that converts grayscale to normal maps that you know of?

Check this tool. You can convert images to normal maps http://cpetry.github.io/NormalMap-Online/


text:
How can I generate an infinite procedural road?
I'm currently trying to make a game where the player races others along an infinite, more-or-less straight, road.
By "more-or-less straight", I mean that the road goes straight ahead (the player can't turn their vehicle to face left or right), but there are bends in the road for them to pass through, as if they were switching from one lane to another on a highway.
There will also be different "areas" to race through (all on the same road), for example, deserts, jungles and over water.
And, finally, there will be gaps in the road for the player to jump over, as well as checkpoints every so often.

Starting with a seed, how can I generate the road ahead of the player as they race? I can't generate the entire road in advance (obviously), but each player needs to see the same thing at the same places along the track.
How can I do this?

What exactly are you asking? If you know that you need to seed your road generator then which part are you having trouble with? How to generate the road dynamically from a seed, without having to pre-generate the entire road?

@FuzzyLogic Yes. I don't necessarily have to seed it, but I do need to dynamically generate a road which is the same for all users. If you'd like to edit the question to make this clearer, please do.

As you know, if you want to generate the road so that both players see the same thing, then you need to start from a common seed value.
If you always start generating the road from the beginning then you can just keep calling your random number generator and the values it produces should be consistent for both players at each step. (Assuming that both players' devices are using the same pseudo random number generator (PRNG), which is not always the case. You may need to provide your own PRNG to ensure that it's consistent for all players).
If you want to be able to resume from different points along the track, then you will need to be able to reseed the PRNG from that point and keep it consistent. You would do this by calculating a new seed at each section (whether you are resuming or not) by using the original seed plus some reproducible value such as distance traveled.
Eg. (pseudo-code)
levelSeed = 1234 // starting seed
distanceTraveled = 100 // keep track of this every frame

// update this prior to adding a new section, obstacle, enemy, etc
// each time the distance is different
rand.setSeed(levelSeed + distanceTravelled)

// example of picking a new trackSegment, after updating the seed value
trackSegment = trackTiles[rand.getInt(numTrackTiles)]

But I don't want the track to be completely random; I'd like "areas" to be of a substantial length each, so that, as its length increases, the probability of switching to another area also increases, and jumps can't be un-jumpable.

What I described would still apply. Just don't randomize the segments all the time. Do it at greater intervals like every 1km instead of every 1m. You could even randomize the distance between changes if you want.


text:
What steps can developers take to improve the graphics of their games?
My understanding is that the differences in graphic quality between games for systems like Xbox One and PS4 and Pixar-style movies stems from that the former are rendered in real-time.
But even with real-time rendering, it looks like some game makers can get rather nice looking results. An example below is about the new Gears of War game:

Above image is from this YouTube video posted by GameSpot. So admittedly it could be from a video (e.g. a promo) that has been rendered more than the actual game.
Anyway so what I wanted to ask is, are games solely dependent on the real time rendering on the target system, or are there some steps developers can take (besides the obvious: start with as good graphics as possible) to improve the graphics in their game?
Edit: here I am referring strictly to in-game graphics.

Are you talking specifically about in-game graphics or cutscenes? While it's getting much better these days, cinematic scenes are much different than in-game graphics, even if they are real-time/mechanim.

@Fuzzy Logic, I have now edited my question (I was referring only to in-game graphics)


text:
How to create rope?
I'd like to re-create this game, but I have no idea how to create the rope, or its influences on the ball.

Basically, there is a rope, "attached", at one end, to the mouse pointer, and at the other end attached to a massive ball. As the user moves their mouse, the rope and ball follow, as if swinging a flail or such in real life.
How would I go about creating a rope as in the above game?
I need to know the basic concepts and physics behind the creation of such a rope, not how to use a pre-existing library to create one. I'd like to be able to implement a rope from scratch, so need to know how it can be done.
Thanks!

The rope in your example is probably just a simple physics-joint that limits the distance of the ball to the mouse-cursor. These joints are typically called "Rope joint" or "Spring joint".
It seems like the ripples in the string are not based on an actual physics-simulation. Most likely this is a bezier-curve where the control points get further pushed away from the central axis when the ball is closer to the mouse-position.
While the accepted answer explains how to create a realistic rope within the physics-engine, it's sometimes preferable to have a much simpler solution (as outlined above). The simpler solution (with just one joint) greatly improves the stability of the simulation. Multiple connected joints that have large forces applied tend to jitter and can result in broken and erratically moving chains of joints.
Of course you can also combine both methods, by creating your rope as such:

A chain of nodes, connected by joints
A rope/spring joint from the first to the last node of the chain that ensures that you can't pull the chain further apart than a given max-distance (one of the main reasons these chains become unstable).

This will result in a more realistically moving chain (that can even react to other objects in the physics-engine) but will require more processing-power than just a spring-joint with "fake" chain-behavior.

Thanks for pointing that out! How would the control points of the bezier be manipulated though, because the example does seem very realistic, not simply like a bezier where it is straightened and "squashed".

I don't think it looks very realistic at all. It just adds some ripples to the rope, it doesn't bend or anything... to me it looks like it's just being straightened and squashed.

But I've noticed that the curves can be at different angles to one another; how is this being achieved?

Add some random offsets to make it look different every time?

Well, you'll probably need some sort of physics-simulation anyway for the movement-calculation. As I said: Modelling the rope completely inside the physics simulation (eg. a chain of connected nodes) can cause instabilities very fast. Less chain segments will increase stability, but then you need to smooth out your rope (eg. use a spline/bezier) or fake it completely. But give it a try, and you'll see. The easiest approach of course is to use an existing physics-engine... (eg. Box2D)

Basically, you'll need to create a physics engine. A rope is conceptually a bunch of "nodes" connected together with springs.
Basically, every tick, each nodes will exert a force on the nodes above and below it proportional to their distance apart (or how far from their comfortable stretch length they are). If you want to attach a ball, just connect it with a spring joint to the bottom node of the rope.
This is a great tutorial for creating a physics engine, but it doesn't really go into constraints or joints.
Here is a tutorial covering basic springs, which should be all you need for a rope like that.
This is a rope created in my (very basic) physics engine. It obviously has some quirks (the weird vibration) but it's generally what you're looking for. When you draw the rope, just don't draw the nodes.
Edit:
To make a good looking rope, a "string joint" is actually much nicer looking and closer to your example. A string joint is basically a spring, but it only corrects the objects when they are too far apart (not when they're too close).
This is my rope with a string joint instead:

"When you draw the rope, just don't draw the nodes." - made me laugh :) Thanks for taking my extreme noob-ishness into consideration. Would the ball just be another node then? Of a greater mass? (Does each node have a mass?)

Yes they do! Generally the best way to intuitively calculate masses is to give each ball a density, and just multiply that by its area. You can always tweak this to get better results in your actual game.

Normally, I'd implement this in an object-oriented language, with a class for a node, with properties density, mass etc., but I'm forced to use a language where OOP is nigh impossible; how would you set up nodes, etc., under these constraints?

To be honest, I have very little experience with non -OOP languages. You could look at Chipmunk2D, which is a physics engine written in C. Obviously, you're going to need some way to store this data in a cohesive unit.

Okay, thank you; last question, is the grey node a node in the sense of the others? What is special about it to cause it to remain still?

The reason that it's grey is that it's "sleeping" (sleep is just an optimization where you don't update an object when it's been at about zero velocity for a while), which is because I set it to having "infinite mass." Basically, I store mass by not storing mass, but the inverse of the mass. This way, I can store 0 as the inverse mass, and the object will never move. I store inverse mass because you may want to represent objects with infinite mass (impossible if you just store mass), but you never really want to represent objects with 0 mass.

This concept is covered in that physics engine tutorial I linked in my answer. It's a really good read and I definitely recommend it even if you're not planning on implementing a full engine!

Does each spring connection need its own object? Or is there a way for the nodes to directly influence one another?

In my engine, I have joint objects (springs are a type of joint) that get updated every tick and exert forces on their two connections. You don't necessarily need this type of architecture, but it might be easier when you have multiple types of joints.

Do you have a link for implementing string joints? That does seem like what I was after...

You could look at SpringJoint in my game library that I've been making. I linked it in my answer. That string joint is actually not built on a spring, but a distance joint. However, they aren't that different if you don't want a stretchy rope.


text:
GameMaker: Studio - Slow down calculations
I currently have an orbital simulator, with a brilliant answer in another Game Development question here, and would like to know how to slow down the calculations of Game Maker, to be able to do more precise ones as my orbits suffer variably intense Apsidal Precession.
Examples of this can be found in games such as Kerbal Space Program and
Universe Sandbox 1/2. In KSP, you have the Max Physics Delta Time which allows slower gameplay, but more calculations. In Universe Sandbox you are able to change the accuracy of calculations causing orbits to go crazy and extremely precise.
How am I able to implement such a thing into GameMaker: Studio?

You can implement a global variable that flips between each mode.
You can reduce the amount of frames that are being rendered per second.
So for example, for a manager object you can have this code in the create event:
//Slow mode
if(global.gameplayMode == 0)
{
    room_speed = 30;
}
//Fast mode
else if(global.gameplayMode == 1)
{
   room_speed = 60;
}

And for calculations
some_stuff = irandom(9001);
if(global.gameplayMode == 0)
{
   moreCalculations();
}

EDIT
//Declare the variable
global.worldPace;

//If you'd like the game to run at half speed then set it to 0.5
global.worldPace = 0.5;

//But if you'd like the game to run at regular speed then just set this to 1
global.worldPace = 1;

And for all of the calculations, just multiply everything by this variable so for example
runningSpeed = 9.8 * global.worldPace;

I've never fiddled with this idea but this is where I'd start.
I'd consider the amount you have to add for geometric functions. You'll have to make sure that whatever value you add, you distribute in the exact same manner when slowed down.
A good example and simple example would be as follows:
If over one frame you move a bullet 2 pixels to the left, with this slow-mo mode you'd now have to split this simple action into two, which means that the action of bullet moving would span over two frames, and in each frame the bullet would only move 1 pixel.
I'd imagine this would be harder to nail down with more complicated functions, so be careful with how you approach them.

I don't think you understand, I'm looking to slow down the calculations ONLY, not the room_speed which is my framerate.

@FinnRayment What does "slowing down the calculations" mean? By slowing the FPS down, you're giving the machine more time to work on calculations than rendering things on screen which in theory would be slower but more accruate like you asked.
Unless you're talking about the game running in a slow-mo mode...?

Yes! The latter. Slow motion mode, where your FPS is constant, but game is slowed down for calculation time.

@FinnRayment I'd just make on global variable that determines the time and multiple it by all of the calculations/variables in the game. I've edited my post above to express what I mean.


text:
Create a normal map using a script? Unity
I don't have a software that can create normal maps from an image so I usually make a grayscale image and then let unity make the normal map from that image. But I can't save the image to use for later, Instead I have to convert it to a normal map every time I use it. So how would I make a normal map from a greyscale using a script? i prefer c# but js works fine.

Hey this function can return a normal map , form an image. It stores the exported image in the Editor Assets folder. You can also specify the strength to increase the bumpiness of the map :)
private Texture2D NormalMap(Texture2D source,float strength)
{
        strength=Mathf.Clamp(strength,0.0F,1.0F);

        Texture2D normalTexture;
        float xLeft;
        float xRight;
        float yUp;
        float yDown;
        float yDelta;
        float xDelta;

        normalTexture = new Texture2D (source.width, source.height, TextureFormat.ARGB32, true);

        for (int y=0; y<normalTexture.height; y++)
        {
            for (int x=0; x<normalTexture.width; x++)
            {
                xLeft = source.GetPixel(x-1,y).grayscale*strength;
                xRight = source.GetPixel(x+1,y).grayscale*strength;
                yUp = source.GetPixel(x,y-1).grayscale*strength;
                yDown = source.GetPixel(x,y+1).grayscale*strength;
                xDelta = ((xLeft-xRight)+1)*0.5f;
                yDelta = ((yUp-yDown)+1)*0.5f;
                normalTexture.SetPixel(x,y,new Color(xDelta,yDelta,1.0f,yDelta));
            }
        }
        normalTexture.Apply();

        //Code for exporting the image to assets folder
        System.IO.File.WriteAllBytes( "Assets/NormalMap.png", normalTexture.EncodeToPNG());

        return normalTexture;
}

If you don't see the exported image immediately, then don't panic. Just minimize the editor and open it again and the image will be there.
If you face any error such as "the image is not readable" , then make sure you change the import settings of the image

Choose texture type as "Advanced"
Check "Read / Write Enable option"
Apply the changes

Do you have any idea how slow this will be?


text:
How can I calculate the bounding box of a 3D model?
I am making a game in OpenGL and Blender and trying to use JBullet as the collision manager. I am using BoxShapes for collisions, which requires a javax.vecmath.Vector3f representing half of the box to create.
How do I calculate the dimensions (width, depth and height) of a Blender model in-game?

You need to find MBB of your model as it seems, why did you go into jbullet and physics in your question? Do you want to use MBB as collision body of your 3D model? Please clarify the question and delete unneccessary parts, however if you are using a lib to use OpenGL or using an inline C part please tell, also tell what is the format of your 3D model

When you're reading the model into your game, you'll be iterating through each vertex of the model. Simply keep track of the max/min for each X, Y and Z axes. Using these values you can find the center of your model as well as the extents. The width is the distance between X min and X max, the depth and height are similarly calculated depending on which axis you're using for which dimension.

Ok, so i am supposed to get the minimum vertex and the higest one for XYZ to get the measures. How exactly is that done? I am using OBJ's exported from blender.

We'd have to know how you're processing the vertices when you import a model. It sounds like you're making your own engine, so at some point, you'd be iterating through all the vertices of your model to read in their positions from a file to memory. That is the time when you'd want to read the position of each and get the minimum and maximum.

I am using(primarily) the engine made by ThinMatrix. In the engine, there is a method which prosesses the entire model(in OBJ format).

@Polarbear0106 Then you need to consult the documentation of the engine you're using to determine how to retrieve the information you're interested in.


text:
How to calculate attacks
I am making a android game, and it is supposed to have attacks.(Note, this game is 2D). I have implemented things like movement to the base, but I am not too sure about the actual attack algorithm. There are supposed to be to bases, one attacker and one defender. I have tried multiple ways, but I cannot get it realistic enough. Here is what has to be a part of it:
    public void attackCalculations(){
        Random r = new Random();

        int[] aa = att.ARMIES;
        int[] ab = def.ARMIES;

    }

I thought about making random casualties based on who have more troops(attacker or defender), but it will not work(tested it, and the casualties were often 0, and it was a loss for the attacker...)
There are ten troops(the ARMIES-variable is a array-int with a max of 10)
    int ARMIES = new int[10];

So, how can I calculate who wins based on all the troops(cannot make a single integer due to different troops)?

First of all, I would make your troops into just an integer: the number of units. If you don't want to do that, just use the array length as a gauge for their troop sizes.
Now the easiest way to do this would be to just take the amount of attacking troops away from the amount defending troops. If the result is negative, the attackers win.. yet if the result is positive, the defenders win and if it's 0 its a draw.
Then to add random casualties, you just add a randomly generated number from -1 to 1 and add it to the result.
Random random = new Random();
int result = defender - attacker;

result += (random.nextInt(3) - 1);

System.out.println(result);
if(result < 0) {
    System.out.println("Attacker Wins");
} else if(result == 0) {
    System.out.print("Draw");
} else if(result > 0) {
    System.out.print("Defender Wins");
}

This is good because, if you ever have 10 Attackers battling 9 Defenders, you have a larger bias towards the attackers (because they have more troops) and yet it still gives the possibility for there to be a stalemate.
As you see these results below show how each of 10 battles turned out, with the attacker having 10 troops and the defender having 9:

As expected, the attacker has won most times because they have a greater amount of troops, and yet there is still a small chance for a draw to occur.
If your troops all have different stats, you can then just take and add them to the result variable as you please.

Try a risk like aproach. N dice launch from attackers sorted by result. M dice launch from defenders sorted by result. For each pair of results count att casualities and def casualities. In risk with the same result defender wins. You can set a max number of comparations per turn


text:
How can I calculate when a spesific amount of time has passed
I am trying to get something to happen, when a spesific amount of time has passed(in my case it is in secounds). I have tried using this method:
   long elapsed = (System.nanoTime()-startTime)/1000000;
   if(elapsed > 1000)
   {
       score++;
       startTime = System.nanoTime();
   }

with the starttime beiing initiated in the constructor. But when I attack(part of the game) the app either:
chrashes
the things the game renders dissapears, and everything turns black.

I have tried asking google, but it in general gave me the save way. Any new improved ideas?

Are you certain that the time related computation is responsible for the crashes?

Do you use startTime somewhere else, especially when dividing?

The startTime is only used for this calculation(otherwise, it would not work). Also, i am 100% positive it is this that caused the chrash(removed the calculation and the app worked)

Unrelated to your crash, for regular timers you should use startTime += 1000000000;. When you use startTime = System.nanoTime(); your timer will slowly accumulate error every update because now is always a little bit after your timer expires.

what kind of crash does it give you? have you tried to see if the
    (System.nanoTime() - startTime)

could be responsible?
try outputing it to the console with a
    System.out.printLn(System.nanoTime() - startTime);

also try outputing your elapsed variables and make sure it's not Null.
having a peak at the part of the code that causes the crash (you talked about attacking) might help. right now your code seems quite fine to me so taking it out of context is hard to debug.


text:
Libgdx Networking (http requests) - Login
I am new to Networking and Databases,
but im trying to learn MySQL and HTTP Requests to create a
user Login for a game.
My goal is to let users create accounts and login to them etc (for Highscores etc). I discovered the Libgdx Net Module and also got my server running with MySQL, Apache and PHP.
I want to use php files to communicate with the Database on the Server.
But my question is (since there is not a big documention for libgdx Network Module):  Where and how can i learn how to create proper HTTP Requests in LibGDX and should i use JSON?   Just give me a hint how to start.
Thanks ;)

Why do you want to do this ? There is no API in java for MySQL commands ? or there is and it is not crossplatform supported by the libgdx libraries ?

@shiro That is what he needs webrequests for. Sent a PHP script to work with the database and receive dynamic data from it. The way I do it is having a Java server in between client and database, that is a lot more work to setup though.

@MennoGouw I am a bit surprised because I have had used a library in C# that could make MySQL connections to a database and could query the database, without any code (like php) on the server side at all.

@shiro jdbc is a java library to do exactly the same. I'm not sure however if it's compatible with platforms other then desktop. I'm using that on the server side of my wip game.

I am using php in-between because its lot more secure than directly connecting to the database.

This is somewhat what I am doing now. I use the KryoNet library also created by Nathan of LibGDX. I have a KryoNet server that my LibGDX app connects to and that server uses the jdbc to connect to a MySQL server locally. So actually without webrequests since my server is local to the DB.
Having a server between the database and your clients is not really necessary though. But I want multiplayer game mechanics that need to be handled on the server. And a TCP connection is a lot faster then webrequests.
Now for your actual question, if you want to use webrequests to run a php script for working with your database then look at the following code.
builder = new HttpRequestBuilder();
        request = builder.newRequest().method(Net.HttpMethods.GET).url("http://yourdomain.com/script.php").build();
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");

final long start = System.nanoTime(); //for checking the time until response
        Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
            @Override
            public void handleHttpResponse(Net.HttpResponse httpResponse) {
                Gdx.app.log("WebRequest", "HTTP Response code: " + httpResponse.getStatus().getStatusCode());
                Gdx.app.log("WebRequest", "HTTP Response code: " + httpResponse.getResultAsString());
                Gdx.app.log("WebRequest", "Response time: " + ((System.nanoTime() - start) / 1000000) + "ms");
            }

            @Override
            public void failed(Throwable t) {
                Gdx.app.log("WebRequest", "HTTP request failed");
            }

            @Override
            public void cancelled() {
                Gdx.app.log("WebRequest", "HTTP request cancelled");
            }
        });

You can also send back XML and HTML if you supply the content-type in the header. Then just use your favorite parser to parse the data in your app. You can just grab it within the listeners httpResponse.getResultAsString() or httpResponse.getResultAsStream() if you like to work with a stream.
This is some php I wrote to receive XML when I wanted the same as you, then I switched over to the client -> server -> database architecture.
<?php
$link = mysqli_connect("127.0.0.1", "root", "", "test");
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><mysql></mysql>");
if (!$link)
{
    $xml->addChild("error", "Error: Unable to connect to MySQL.");
    $xml->addChild("error", "Debugging errno: " . mysqli_connect_errno());
    $xml->addChild("error", "Debugging error: " . mysqli_connect_error());
    exit;
}

$xml->addChild("success", "Success: A proper connection to MySQL was made!");
$xml->addChild("success", "Host information: " . mysqli_get_host_info($link));

//To send the xml data back:
print($xml->asXML());

mysqli_close($link);
?>

Take note that you do have to change the header to receive xml data in your app.

Thanks for your detailed answer. Using Kryonet sounds very interesting to me, because i am already using Kryonet to provide Multiplayer. I am currently running Kryonet on the Android client (which connects to..) and on my Debian Server (as a Jar), which embodies the Game-Server.
By using Kryonet i could just build this directly into my main Server Project.
Would you mind to explain this a bit more in detail how you are using this strategy?

@Sand When I need something from the client I sent a request to the server and start listening for the required "packet". When the server receives the request it uses jdbc to make a local database connection. It creates a object from the collected data and sends that over to the client who requested it.

I understand this and i already implemented it ;)  I just wanted to know if i need to take note of something special. But thank you.


text:
Dealing with Spritesheets - resizing
Let's say that I have a spritesheet with 4 sprites (standing, breathing player).
When I load it with
player_bitmap = BitmapFactory.decodeResource(resources, R.drawable.player_standing);

it sets it's width and height to for example 100/50 and I have to divide it by 4 and I get four sprites 25x50.
Problem is here that when I switch the app to tablet (I was on phone) sprites have different sizes when loaded.
How to solve issues like this?
Thank you

It seems as though the pixel density for your phone and tablet are different.
If so a few of options are,
1) Have a set of spritesheets created for varying pixel density displays and pick the closest one that matches the pixel density it was created for. You could end up with a lot of spritesheets
2) Scale your sprites when you draw them.
You can use a mixture of both techniques.
If your phone has a pixel density of 100, and your tablet has a pixel density of 200, then your sprites would seem half the size on the tablet. In this case if you chose option 2 then you'd need to double the scale
You can find a handy PPI list for various devices here


text:
Delay between bullets java - new Thread
Let's say that I have a cannon on the bottom of the screen that shoots balls to the click direction. I also have some collisions algorithms and here comes the problem. I am trying to implement an OnHold method that shoots continously and it works, but I think that I need to make shooting on another Thread. I've implemented this in two ways:
 1. I was checking the delay and if it passed I shot
 2. I was checking previous ball y position and when it floated away I shot
The problem comes here that when I hold the button for some time, for example. 5 balls are okay (they're near each other - not colliding) and then comes a ball that is late O.o
I don't know how to implement a new Thread within these MotionEvents. If is there someone who can point me (if should I make in on Threads or something) a solution - I would be grateful :)
  @Override
public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub

    touched_x = event.getX();
    touched_y = event.getY();
    int i = 100;

    int action = event.getAction();
    if (action == MotionEvent.ACTION_DOWN) {
        startShootTime = new Date().getTime();
        running = true;
    } else if (action == MotionEvent.ACTION_MOVE ) {
        shootTime = new Date().getTime();
        // movement: cancel the touch press
        running = true;
        touched_x = event.getX();
        touched_y = event.getY();
       // && game.gameLoop.current_time - shootTime > 400 &&
              //  game.gameLoop.current_time - startShootTime > 100
        //  while(actionUpflag) {
        int size = game.gameLoop.balls.size();
        if(size == 0){
            game.gameLoop.balls.add(new Ball(metrics.widthPixels, metrics.heightPixels, touched_x, touched_y, game.gameLoop.ball_bmp_width, metrics.heightPixels-game.gameLoop.ball_bmp_width/2));
        }else if(size > 0 && game.gameLoop.balls.get(size-1).image_center_y < metrics.heightPixels - game.gameLoop.ball_bmp_width-50)
        game.gameLoop.balls.add(new Ball(metrics.widthPixels, metrics.heightPixels, touched_x, touched_y, game.gameLoop.ball_bmp_width, metrics.heightPixels-game.gameLoop.ball_bmp_width/2));

        invalidate(); // request draw

    } else if (action == MotionEvent.ACTION_UP) {
        running = false;
    }

    return true;
}

No. You should not use threads for this.

@msell then what should I use here? Thanks for the response

It looks as if you have some kind of game loop running always? And so the game has a cannon object? If this is the case, you could use the touch event to inform the cannon update.
Please excuse my pseudo code..
in the event
public boolean onTouchEvent(MotionEvent event)
{

    touched_x = event.getX();
    touched_y = event.getY();

    game.gameLoop.cannon.fireAtTarget(x,y);
}

the cannon class
   void cannon::fireAtTarget( x,y )
   {
     firing = true;
     targetx = x;
     targety = y;
   }

the cannon update
void cannon::update( timeNow )
{

    if( firing && (timeNow-lastTimeFired > 0.5) )
    {
        // fire at targetx, targety.
        lastTimeFired = timeNow;
    }

}

Dont forget to disable firing in the touch up event

Working like a charm - Im adding balls while updating gameloop thread.


text:
Are hard coded "rooms" better than dynamically generated on a smart phone, from performance point of view
This question pertains to a type of platform/maze game (made with Unity 5) for typical smartphones (iOS/Android).
This game has following characteristics:
 1. an upper limit (about 100) on the amount of rooms
 2. 3-5 different "levels", each with a different amount of rooms
 3. the shape and type of the "ground" in each room is dynamically generated
 4. each room has some items that are dynamically placed in the room but are generated from a prefab
A rough idea on the rooms in this game is given in below screen shot.

In that image only the platforms (black and white tiles) and the ground (light brown) would be shaped by an algorithm. The other objects shown in the image are prefabs that would be located somewhere in the room by an algorithm.
But considering that this game would not exactly be an infinite runner, and since it should run on smart phones, would it be better from performance perspective, to create 100 hard coded rooms instead?

It wouldn't be that much of a performance drag. The user would have to wait in order for the level to generate, but other than that it should perform the same as a pre-made level.
100 custom made levels on the other hand would load faster but would take up more storage.

thanks @Daniel. When you say that the 100 custom levels would "take up more memory", do you mean storage memory (as opposed to RAM)? I am asking because would it not be possible to have the game load the rooms as it needs them (or keep only the rooms that are around the players current location in RAM)?

Both methods would use the same RAM. The custom 100 levels would take more storage memory.

We call it "storage" not "storage memory." The amount of space, honestly, would be trivial (kilobytes to megabytes).

What I would do in these situations with the new Unity 5.3.3 patch with the new Scene Management is to create a level editor and save the rooms as scenes. It is fairly easy to create editor functions, you can learn here.
If you are worried with storage, you can make a level editor that converts and store the levels as a .txt file but that would be as asshes999 say, trivial. But I would say the scene approach is better.
Other advantages of making a level editor, is you can extend the level editor functions and make unit tests.


text:
OpenGL: Objects wont draw at certain angles while using lighting(shaders)
I was following this tutorial (http://www.lighthouse3d.com/tutorials/glsl-12-tutorial/point-light-per-pixel/) but when the camera is at a certain angle, if I had alpha test and blend enabled the cube i have in the scene wouldn't draw, otherwise they would be black(if alpha and blend was disabled) Any thoughts on what's going on?
here is some relevant code:
glClearColor(0.6, 0.6, 0.6, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(80, (float)window.getSize().x / (float)window.getSize().y, 0.01f, 1000.0);
glMatrixMode(GL_MODELVIEW);

glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
//glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glEnable(GL_ALPHA_TEST);
//glAlphaFunc(GL_GREATER, 0.1f);

glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
    .....

void Lighting(Camera cam, sf::Vector3f Pos) {
GLfloat amb[] = {0.2, 0.2, 0.2, 1};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, amb);

GLfloat diff[] = { 1, 1, 1, 1 };
GLfloat pos[] = { Pos.x, Pos.y, Pos.z, 1 };
glLightfv(GL_LIGHT0, GL_DIFFUSE, diff);
glLightfv(GL_LIGHT0, GL_POSITION, pos);
}
....
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
cam.up(delta, window);
Lighting(cam, Pos);
sf::Shader::bind(&shader);

cube.draw();
cube1.draw();
window.display();
sf::Shader::bind(NULL);

draw function for cubes:
glPushMatrix();
    glTranslatef(pos.x, pos.y, pos.z);
    glBegin(GL_QUADS);
        glColor3f(color.r / 255, color.g / 255, color.b / 255);

        glVertex3f(0, 0, 0);
        glVertex3f(width, 0, 0);
        glVertex3f(width, height, 0);
        glVertex3f(0, height, 0);

        glVertex3f(width, 0, 0);
        glVertex3f(width, 0, -length);
        glVertex3f(width, height, -length);
        glVertex3f(width, height, 0);

        glVertex3f(0, 0, -length);
        glVertex3f(0, 0, 0);
        glVertex3f(0, height, 0);
        glVertex3f(0, height, -length);

        glVertex3f(width, 0, -length);
        glVertex3f(0, 0, -length);
        glVertex3f(0, height, -length);
        glVertex3f(width, height, -length);

        glVertex3f(width, 0, 0);
        glVertex3f(0, 0, 0);
        glVertex3f(0, 0, -length);
        glVertex3f(width, 0, -length);

        glVertex3f(0, height, 0);
        glVertex3f(width, height, 0);
        glVertex3f(width, height, -length);
        glVertex3f(0, height, -length);
    glEnd();
glPopMatrix();

Without digging too deep, I noticed a couple things in your code:
First, you're using old style OpenGL functions (pre-3.0) which haven't been relevant for years.  I suggest studying from a more up-to-date tutorial site, such as this one I've been using: http://ogldev.atspace.co.uk/
Second, in your call to glColor3f (which is outdated) you're dividing your color by integers.  I can't see your declaration of 'color' but if it is also integral then all those values are being rounded down to 0 so your color is all black.  Get in the habit of specifying things as floats when that's what they're expected to be, like this: 256.0f


text:
Server/Client architecture
I have high experience In Java and Networking. Our team have built a effective server that can create thread-pools managing many players. But we have hit a brick-wall. The way our server works is that our clients directly all just connect to the server. The client sends information to the server. For example, Client 004 pressed W. And the server calculates and responds. But here's the problem. What exactly do we send over the data stream? Do we send strings and decode them on the client/server side, or serialize objects? Sadly that question is very opinion based. So let me re-phrase it. What data do we send over the stream? For example, you can use W,A,S,D To move around. Im guessing it should look like this.
User Pressed W > Client sends string saying w to server > Server calculates movement > Server sends string saying player position to player > User updates players position.
But then we have to render other players. So we thought about this
User MPressed W > Client sends string saying W to server > Server calculates movement > Server checks if any others players are in the area > Server saves data of all players and yourself into a string and adds positions and sends to client.
Fair enough. But imagine if the server had to send over information, like the other players clothing, their health, mana, position, current animated frame.
The string might look like this:
"Bob, 12, 321, 391.34, 2914.2, Left, 0, False, null, null, sword, null, null"
Just for one player! To be sent over. The string concept is becoming long and tedious.
I have re-wrote this several times. And I still do find it confusing to understand the question myself.
But to shorten it down. How do I create a system where its a mmo really.
We've created the server, client art. We've payed for a large server with ddos protection. But we don't know what to send over the sockets.

What if I want to use the arrow keys? It'd be crap.
You have the clients send updates like "I am at x moving at speed p and turning at rate m"
The server should so some quick bounds checking (to prevent cheating) then pass those updates on ASAP.

Clients should query what they need, for example "get player list" (as some command) might cause the server to send back a list (in whatever) format of the players AND their positions
The client will then be like Alec is closest, followed by Bob and be like:

> Describe Alec
< Health: 100, max health 120, clothes.....
> Describe Bob
< (so forth)

Obviously don't send these as strings. State machines and UDP are the way to go.
Like expect 4 bytes to be some sort of "command ID", if the command ID is 13 (get player list) then expect 2 bytes (the number of players, unsigned int) then expect 3 floats, a number for the length of the name and that length number of bytes. - do this for each player.

But you should never trust the client to handle anything! Not a single mathematical operation!

@ElliotBewey the client should be doing stuff like that. Otherwise you can't really expect even 2 frames per second. Quite often on online FPSes two people will shoot each other, consequences of special relativity.


text:
UDP server and two clients
So - my whole knowledge comes from google and stackoverflow. I'm trying to create an UDP server (with two slots per new instance of the game) and clients.
My problem is here that I totally don't know where to start. I can't find and tutorial that shows how to connect two players with a server via UDP - and yes - it has to be UDP cause of the game mechanics. I wrote this:
public class Server {

   private static HashSet<Integer> ports = new HashSet<Integer>(); // these     are player's IDs
   static ArrayList<InetAddress> addresses = new ArrayList<InetAddress>();
   public static boolean player1_active = false, player2_active = false;
   public static PlayerCredits p1, p2, temp;
   public static void main(String[] args) throws Exception {

   // The default port
    int serverport = 8888;

    DatagramSocket udpServerSocket = new DatagramSocket(serverport);
        DatagramPacket sendpacket;
    System.out.println("Server started...\n");

    while(true)
    {

        byte[] receiveData = new byte[1024];

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        udpServerSocket.receive(receivePacket);

        String clientMessage = (new String(receivePacket.getData())).trim();

        System.out.println("Client Connected - Socket Address: " + receivePacket.getSocketAddress());
        System.out.println("Client message: \"" + clientMessage + "\"");

        InetAddress clientIP = receivePacket.getAddress();
                    addresses.add(clientIP);

        System.out.println("Client IP Address & Hostname: " + clientIP + ", " + clientIP.getHostName() + "\n");

        // Get the port number which the recieved connection came from
        int clientport = receivePacket.getPort();
        System.out.println("Adding "+clientport);
        ports.add(clientport);

        // Response message
        String returnMessage = clientMessage.toUpperCase();
        System.out.println(returnMessage);
        // Create an empty buffer/array of bytes to send back
        byte[] sendData  = new byte[1024];

                    temp = new PlayerCredits(clientport, clientIP);

                    if(!player1_active){
                     p1 = new PlayerCredits(clientport, clientIP);
                     player1_active = true;
                    }

                    if(temp.port != p1.port && temp.ad != p1.ad)
                     if(!player2_active){
                        p2 = new PlayerCredits(clientport, clientIP);
                        player2_active = true;
                    }

                    DatagramPacket sendPacket;
                     if(p2 == null){
                         String awaiting = "WAITING FOR SECOND PLAYER";
                         sendData = awaiting.getBytes();
                          sendPacket= new DatagramPacket(sendData, sendData.length, p1.ad, p1.port);
                            udpServerSocket.send(sendPacket);
                     }
                         else{
                         String awaiting = "SECOND PLAYER INCOMING";
                         sendData = awaiting.getBytes();
                            if(p2!=null){
                            sendPacket = new DatagramPacket(sendData, sendData.length, p2.ad, p2.port);
                            udpServerSocket.send(sendPacket);
                            }
                            sendPacket = new DatagramPacket(sendData, sendData.length, p1.ad, p1.port);
                            udpServerSocket.send(sendPacket);
                     }

        }

}
public static class PlayerCredits{
    int port;
    InetAddress ad;
    public PlayerCredits(int p, InetAddress a){
        this.port = p;
        this.ad = a;
    }
}

So - for now I have two people connected - but as you will probably say - it's WRONG. Cause I know - it is :D I need to somehow implement every player on the Multisocket or something (or connect them via TCP and then listen on a new thread with a new datagram).
If there is someone that could help and tell me, how it should be done like in 3 steps like (I don't need code):

Connection with TCP
Create new threads with players and listen on UDP
Start the game when 2 players are connected

Also, how to stop the 'third connection' and redirect it to a new game instance? (cause it's 1v1).
I would be so grateful. I will have networking in two years in college, but I want to learn it.

The reason for the roadblock you are hitting is that you try to do something which does not exist. As a stateless protocol, UDP doesn't have "connections".
Because a UDP datagram is not explicitly tied to a connection, you need to find out by yourself from which client an UDP datagram originates. One way to do this is by calling getPort() and getAddress on the DatagramPacket and use that information to find out from which player it originates.
When you then want to forward the information from that datagram to the other players, you send them new datagrams with their respective ports and address of those players.
Because UDP is stateless, you need to implement your own state management to keep track of which players are currently connected. A good way to do this is by having some collection of currently connected players. When you receive a new message, check if a player with that IP and port is already in the collection. If not, add them. Remove players when they send a special "disconnect" message or when they didn't sent any messages for X seconds (timeout).


text:
Spline type to achieve a specific result
Is there a type of spline which can produce (approximately) the following result given the specified points indicated. I want to be able to specify how curved the corners are from the "centre points" so that I get "very square" corners to "very round" corners. Sorry about my shakey hand ! Points along a line should produce (roughly) a linear curve.
I found quite a few questions and answers online about this but they all seem to be B-spline related, and don't (I think) quite capture my constraints. If anybody knows what I'm looking for, direction to an online reference/article would be great.
My points always appear on an integer lattice (grid), and are always equally spaced.
I'm looking for something low complexity, but which I can pass a value, say t in [0,1] and returns the (x,y) position of the curve at that time. I realise I could probably build a function like this piece-wise, but wondered if there is a ready made spline solution (piece-wise equation) which could achieve the same result.
Maybe B-splines or NURBS are the answer, but maybe they are heavy on computation too...

Given Sirisian's answer below, I suddenly realised how Bezier curves work. Wow they really are a clever idea!

Everything seems centred around a single t value, e.g.
l1(t) = a+t(b-a)
l2(t) = b+t(c-b))
m(t)  = l1(t)+t(l2(t)-l1(t))

We can expand m to simplify if necessary.

I think B-Splines give a nice result, e.g. see below. It also has the advantage of not being restricted to a uniform grid. Not sure about speed of computation yet though...

Seems like a simple quadratic Bézier curve would be sufficient.
https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_curves
Implementation-wise you'd just draw a line for horizontally or vertically connected nodes and then a curve for the other cases.
An alternative that would be more complex would be use to use an arc like in the SVG spec:
http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands
There are implementation details in the spec for how it functions.


text:
Find x and y position with angles in 3D world
I'm actually creating a Tracking Camera (or 3rd person camera), and to do so, I used two angles (X and Y) for the rotation of the camera and an other floating value for the distance between the target and the camera.
The camera system works fine, but I am searching a way to calculate the position of the correct position of the camera (for debug purpose only)
Do you have an idea of how I can do to figure it out?
This is the camera update function:
public void Update(GameTime gameTime)
{
  this.View =
    Matrix.CreateTranslation( 0, 0, 0 ) *
    Matrix.CreateRotationY( MathHelper.ToRadians( this.RotationAngle ) ) *
    Matrix.CreateRotationX( MathHelper.ToRadians( this.ArcAngle ) ) *
    Matrix.CreateLookAt(
      new Vector3( 0, 0, -this.Distance ),
      this.TrackingPosition,
      Vector3.Up );

  Viewport _viewport = this.graphicsDevice.Viewport;
  Single _aspectRatio = (Single)_viewport.Width / (Single)_viewport.Height;

  this.Projection = Matrix.CreatePerspectiveFieldOfView(
    MathHelper.PiOver4,
    _aspectRatio,
    NEAR_PLAN, FAR_PLAN );

  // Find x and y
  this.Position = new Vector3( 0, 0, -this.Distance );
}

polar to cartesian in 3d (spherical coordinate system)
x = r * sin(theta) * cos(phi)
y = r * sin(theta) * sin(phi)
z = r * cos(theta)
where theta and phi are your x , y angles

Hello, thank you for your answer. I just implement those formulas and it works perfectly. Thank you!


text:
Platformer collision problems
I am working on a platformer 2D, and i am currently focusing on collision. I have the actual rectangle(class: Rect) and i can detect if the player-model is intersepting it. However, when it comes from the side, that is when the problems appear: i can prevent it from going down after the interseption but i cant prevent it if it intersepts with the edges. how can I  make a better collision system?
EDIT:
I have worked a little on a system, but it doesnt work. Help me improve this:
for(Platform p : game.platforms){
            if(Rect.intersects(getBounds(), p.getBounds())){
                coll = true;
                int px = p.x;
                int py = p.y;
                if((x + 100) >= px  && (x + 100) <= px + 10){
                    x = px - 101;
                    y += 100;
                    Toast.makeText(game.c, "if(x + 100) >= px  && (x + 100) <= px + 10)", Toast.LENGTH_LONG).show();
                } else if(y  <= (py + 1) && y  >= py + p.height + 10){
                    y = 0;
                    Toast.makeText(game.c, "if8y <= (py + 1) && y  >= py + p.height + 10)", Toast.LENGTH_LONG).show();
                } else if(y  >= py ){
                    y = py - 100;
                    Toast.makeText(game.c, "if(y >= py", Toast.LENGTH_LONG).show();
                }
            }
        }
        if(!coll){
            y += 6;

        }else{

            heightJumped = 0;
            canJump = true;
            isInAir = false;
            jumping = false;
        }
        coll = false;
    }

At the first frame where the moving rectangle intersects with a static rectangle, you can move it towards the opposite direction, so that it barely touches the static rectangle and no longer intersects.

It's about depth resolution. Find the depth intersected on each axis of the rectangle and resolve the smallest depth. There are still problems with that solution. But you should try this first.

This is my perfectly working 2d collision system (C++). Maybe it helps. I have also had the problem with wrong colliding from sides but finally solved it.
So, I have a rectangle of player with 64px width and height.
"posX" and "posY" are its center coordinates.
The parameters of the "colCheck" function are the sides of the rectangle which we want to check if colliding.
float difference = 0; //final difference between player and object (inside)

short Player::colCheck(float left2, float top2, float right2, float bottom2)
{
    short _returnVal = 0;     //Return value
    float left1 = posX-32;    //Player Left
    float right1 = posX+32;   //Player Right
    float top1 = posY-32;     //Player Top
    float bottom1 = posY+32;  //Player Bottom

    if(left1 < right2 && right1 > left2 && top1 < bottom2 && bottom1 > top2)
    {
        if(right1 > left2 && left1 < left2 && right1-left2 < bottom1-top2 && right1-left2 < bottom2-top1)
        {
            difference = right1-left2;
            _returnVal = 1;
            //Player collides from left side of the object
        }
        else if(left1 < right2 && right1 > right2 && right2-left1 < bottom1-top2 && right2-left1 < bottom2-top1)
        {
            difference = right2-left1;
            _returnVal = 2;
           //Player collides from right side of the object
        }
        else if(bottom1 > top2 && top1 < top2)
        {
            difference = bottom1-top2;
            _returnVal = 3;
           //Player collides from top side of the object
        }
        else if(top1 < bottom2 && bottom1 > bottom2)
        {
            difference = bottom2-top1;
            _returnVal = 4;
           //Player collides from bottom side of the object
        }
    }

    return _returnVal;
}

        //Parameter 'cols' (=collisions): cols [index] [side]
        //cols[x][0] -> left side
        //cols[x][1] -> top side
        //cols[x][2] -> right side
        //cols[x][3] -> bottom side
        //Parameter 'size': count of the collisions
        void Player::colReact(std::vector<std::vector<float>> cols, unsigned int size)
        {
            for(unsigned int i = 0; i < size; i++)
            {
                short ret = colCheck(cols[i][0], cols[i][1], cols[i][2], cols[i][3]); //check if collides and get the return value
                if(ret > 0) //if is colliding
                {
                    float changeX; //variable to add to players X coord.
                    float changeY; //variable to add to players Y coord.
                    if(ret == 1) //collides from left
                    {
                        changeX = -difference;
                        changeY = 0;
                    }
                    else if(ret == 2) //collides from right
                    {
                        changeX = difference;
                        changeY = 0;
                    }
                    else if(ret == 3) //collides from top
                    {
                        changeX = 0;
                        changeY = -difference;
                    }
                    else if(ret == 4) //collides from bottom
                    {
                        changeX = 0;
                        changeY = difference;
                    }
                    posX += changeX; //add the -difference value to players x coord.
                    posY += changeY; //add the -difference value to players y coord.
                }
            }
        }

Hope it's a helpful source.

Sorry for a late responce, but could you try to explain the code? I use java so i need to know exactly how it works in order to use it

I've commented on their right side. But I repeat it clearly, You have to use the function "colReact(collisions[], collisionCount);" in your update loop. and your player object (as Rectangle) has the position coordinates "posX" and "posY" (They are its center coords.). the function "colCheck(..)" is just the logic side of collision check. It's returns whether it's colliding and at which side of the collision object. And colReact avoids your player to go over of that collision object.
If your players (rectangle) width is 64px, then you have to use the same variables like in the func. "colCheck"

what about colliding with more complex meshes?


text:
How to develop a good game project?
I have enough experience in both C++ and Java, since I've been working on them a lot. My graduation project is, in my case, a game (I still have almost 8 months remaining). I already took down the basic ideas behind it, but I'm still unsettled on how to implement the whole project. The best method, in my opinion, was to perform low level operations such as window handling and OpenGL rendering using libraries implemented by me in C++ and more game-oriented features with Java.
So, basically I'm headed to create the game engine with C++ and any game related code with Java, through the use of the Java Native Interface to perform engine calls from the JVM. Can this be considered a good idea or it is that bad?

Very interesting question but why not use an already made and currently still developed library in java, such as libgdx ? Is it not allowed ? Or you just want to do this for the experience ?

Questions like this that ask "is this a good idea?" (or related, questions about how to start a project and which technology to use) are generally discussion-oriented and are considered off-topic here. There's nothing that seems immediately terrible about your plan, but if you want to ask about it you may be better off in the [chat] or on a forum like GDNet.

All I wanted was just an answer about the correctness of the technology I described, anyway thanks for support

@Shiro I want to do in that way for experience

If it's your first game project, and you're on a schedule, I would put aside "R&D" ("for experience") and stick to a single project, "making a game". You'll encounter enough issues only with the development of your game, I would not add the BIG overhead of designing/programming a cross-language architecture and designing and writing a rendering engine. KISS, keep it simple and small. At least at first, until you know more where you're going. And if it is your first game project, "performance" is not a good reason, IMHO, to mix c++ and java.

It's not my first time I've been making games, I already made other game engines by myself, completed one or two projects and I have even been working with modern OpenGL. Performance is not my issue, and I just thought to do it that way to add some more things to the project, since it's really a simple game to make.

Oh, well in this case, as it's been said, it's pretty hard to tell. Depends on the goal you aim. Do you want to compare the same game with the same architecture, but one using a c++ base engine and the other with a Java base engine, and compare if one outperforms the other? Or just see if you're able to do it? Really, it's too opinion based, or too broad unfortunately.

The main purpose of the question was to understand if making everything with Java (so using LWJGL) was better or worse than dividing the architecture by implementing the engine in C++ (so using a different library) and implementing the game logic with Java

I explained what I really needed to ask in the wrong way, I'm sorry