texts: Euler angles to Cartesian Coordinates for use with gluLookAt

texts:
I have searched all of the internet but just couldn't find the answer. I am using LibGDX and this is part of my code that loops over and over:

public void render()
{
    GL11 gl = Gdx.gl11;

    float centerX = (float)Math.cos(yaw) * (float)Math.cos(pitch);
    float centerY = (float)Math.sin(yaw) * (float)Math.cos(pitch);
    float centerZ = (float)Math.sin(pitch);
    System.out.println(centerX+" "+centerY+" "+centerZ+" ~ "+GDXRacing.camera.position.x+" "+GDXRacing.camera.position.y+" "+GDXRacing.camera.position.z);
    Gdx.glu.gluLookAt(gl, GDXRacing.camera.position.x, GDXRacing.camera.position.y, GDXRacing.camera.position.z, centerX, centerY, centerZ, 0, 1, 0);

    if(Gdx.input.isKeyPressed(Keys.A))
    {
        yaw--;
    }
    if(Gdx.input.isKeyPressed(Keys.D))
    {
        yaw++;
    }
}

I might just be bad at the math, but I dont get it. Does someone have a good explanation and an idea about how to deal with this? I am trying to make a first person camera. By the way, the camera is translated by +10 on the Z axis. Currently when I run the application, this is what I get:

Watch video in browser  |
Download video
(for those who cant download the video, everything shakes in a clockwise/anticlockwise action, depending on if I increase or decrease the Yaw value)

-Thank you.

[edit]

I fixed it and posted an answer below if you want to see how I did it. This would have not been possible without Sam Hocevar's answer, so big props to him :D


texts:
If you have for example an MMO with 2000 players, and players are constantly removing / creating / swapping items (and doing some other important things that can't be lost).

If the updates are saved instantly in the database, since they are too many, the database dies. If you save them every "x" minute, there's a window where if your server app dies, players may lose items, and sometimes they may be expensive, let's say 100$, so that can't happen.

Is there a design or a guide I could read that handles this issue? The games I play today do not have that problem.


texts: Ipad - actionsheet not showing all buttons in landscape mode when keyboard is present

texts:
I am developing an Ipad application. It supports both landscape and portrait mode. The app has keyboard.It also shows an action sheet with 4 buttons when required. In portrait mode it works perfectly. But in landscape mode action sheet only show 2 buttons when keyboard is there .Without keyboard it show all 4 buttons.
Any solution?


texts: Is SDL2 alone capable of dynamic (or deferred) lighting?

texts:
I'm talking about JUST SDL2, not OpenGL or DirectX.
Would drawing deferred lighting bulk the CPU up and how would it be done?


texts: XNA How to detect collision between 2d sprites and 3d primitives (not models)

texts:
My current status

I have already read some tutorials about 3d collision.
I know how ray trace works and how to convert mouse follow a vector to track the closest object that collides with out vector
I have also worked with 2d collisions before and I've seen some collision samples from "apphub".

My Problem

My problem is mainly because all the tutorials I have read are about collisions over 3d models on .fbx format but I don't use model files... I use simple primitives... So what methods do I need to check to be able to know if a 2d sprite has collided with my 3d isometric triangle? Also bounding box will have blank spaces outside my triangle borders that will return a false positive.

Main Questions

Is there a way to transform primitive into 3d models so i can use Ray.Intersect?
Do I need to  transform the vertices into 2d points and then check if any pixel from  sprite is between these 3 lines?
I'm also aware of boundingbox but it doesnt seems to be a good solution since we are talking about a triangle not a square. Or should I create a bounding box around the 2d sprite and then try to collide over all the Z's?

If you need clarification please let me know. I'm not very good in explaining myself.

thanks


texts: I've heard about this concept, but what is it?


texts: Tone mapping and eye adaptation - pale colors and darker image

texts:
I'm trying to implement tone mapping along with eye adaptation and HDR. Actually I implemented this already but I'm not satisfied with result and I think that I made something wrong.

My final image (before postprocessing) I store in half float texture. I have also 2 helper textures. The first one stores log luminance and avg, min and max color of it in last mip-map. The second one stores adapt value which is computed as:

prevLum + (avgLum - prevLum) * (1.0 - exp2(-adaptionRate))

where prevLum is previous adapt value (size of this texture is 1x1). Log luminance texture is R8B8G8 format and the second one is R8. In tutorials I saw that half float textures are used but in my case I've got too bright images (almost white).

In the final postprocess shader I'm using all of there values to obtain eye adaptation and tone mapping using this code:

float autokey(in float lum) {
    return 1.03 - 2.0 / (2.0 + log10(lum + 1.0));
}

float hejl(in float color) {
    float x = max(0.0, color - 0.004);
    return (x * (A * x + B)) / (x * (A * x + C) + D);
}

float adaptedLum = texture(adaptedLuminance, vec2(0.5)).r;
float exp = exposure * autokey(adaptedLum) / adaptedLum;
result *= exp;

result.xyz=RGB2xyY(result.xyz); // conversion to CIE xyY

result.z = hejl(result.z);

result.xyz=xyY2RGB(result.xyz);

And here is my results:

eye adaptation and tone mapping turned on

eye adaptation only

tone mapping only

everything off

As you can see when tone mapping is turned on bunny color is paler. And when eye adaptation is turned on final image is much darker. Could someone explain me what could cause that, because I think that something here is wrong. Maybe it's something with color spaces which I don't understand well? Or with bloom which is applied before tone mapping and eye adaptation?

I have also another strange behaviour with eye adaptation. When I'm looking on dark areas, background (sky) get brighter. It's ok but it happens always when the center of camera is on black area (no matter how far camera is from this area).

I basen on implementation included in projects on this pages:
John Chapman,
Nutty Software


texts: How to decide whether to use a physics engine for a platformer

texts:
I'm planning on creating a 2D platformer and doing some research to make sure that when I get started, I avoid making some poor decisions. Something I've seen come up multiple times is that I should consider writing my own physics for a 2D game instead of using the physics provided by an engine. For example, in this question, multiple answerers tell the OP to write their own character controller logic instead of using the physics built into Unity.

Why is this advice common? What benefit would I gain by writing my own physics code? And how do I decide whether writing my own physics is appropriate for my game?


texts: Friction due to gravity in an impulse based physics engine

texts:
In my physics engine, I'm using impulses to solve collisions. I'm basing all calculations on these equations:

impulse = desired_velocity_change * mass
impulse = force * time
friction_force <= normal_force * coefficient

If an object moves along flat ground (infinite mass), after integration it'll be moving slowly "into" the ground due to gravity. This means that the impulse needed to react to that (given the restitution equals 0) will be the velocity in the direction of the contact normal, multiplied by mass.

The issue here is that gravity is a constant acceleration, which means that the object, no matter the mass, will always "dip" by the same amount given a constant frame rate. So the mass is never a factor in this situation, outside of the impulse calculation, which is just a flat velocity change.

Now, I can use impulse to calculate the force that was needed to react to the collision, this force can then be used in the friction equation as such:

friction_impulse / time <= normal_impulse * coefficient / time

Since time is always greater than 0, I can just multiply both sides by it, and then I can use the impulse equation, as such:

planar_velocity_change * mass <= velocity_change_along_normal * mass * coefficient

And again, I can just remove mass from the equation, which leaves me with:

planar_velocity_change * mass <= velocity_change_along_normal * mass * coefficient

This is the desired velocity change along the contact surface due to friction. The issue is, obviously, that none of this depends on mass, which means that no matter how heavy or light an object is, it'll always continue sliding along the surface by the same amount given a constant initial velocity.

What am I missing? It really looks like there's a logical mistake here. Should the dynamic friction depend on the mass in the first place? Moving a heavy object requires higher force, so static friction should be modeled properly, since it just flat-out removes velocity, though it'd be nice to hear if this has merit or just "looks good".


texts: Submit scores for multiple players to Game Center from one iPhone

texts:
I have a quiz game, which i would like to integrate Game Center for. This is a "local" multiplayer game with the possibility to play six players per match.

Is it possible to submit scores to the Game Center leaderboard for all six players in this setup given that it is only one player, the one that owns the device, that is logged on to Game Center?

If so, how is that done?


texts:
At present I load my font for my game in with @font-face

For instance:

@font-face {
    font-family: 'Orbitron';
    src: url('res/orbitron-medium.ttf');
}

and then reference it throughout my JS implementation as such:

ctx.font = "12pt Orbitron";

where ctx is my 2d context from the canvas.

However, I notice a certain lag time while the font is downloaded to the user.  Is there a way I can use a default font until it is loaded in?

Edit -

I'll expand the question, because I hadn't taken the first comment into account.  What would the proper method of handling this be in the case that a user has disabled custom fonts?


texts: How to play two 2D animations at the same time?

texts: I have a "burn" animation and a "poison" animation for when the player is burnt or poisoned respectively. I want to play both animations at the same time when the player is both burnt and poisoned. From what I've read this is supposed to be possible with layers, but I can't get it to work.


texts:
I simply want to pick a few spheres in my scene using the mouse-ray. I have implemented(copied most of it but with little understanding) a ray-sphere collision code. Also I have implemented the code for converting the mouse window coords to OpenGL coords. And constructed the mouse function. I have a ray class. In other words I have made everything, but sth isn't working...

So, there is the ray-sphere collision code:

bool Sphere::CheckRayCollision(Ray mouseRay)
{
     double discriminant, b;

     b = -DotProduct(mouseRay.GetOrigin(), mouseRay.GetDirection());
     discriminant = b * b - DotProduct(mouseRay.GetOrigin(), mouseRay.GetOrigin()) + this->radius * this->radius;

     if(discriminant < 0)
     {
         std::cout<<"disc"<<std::endl;
         return false;
     }
     discriminant = sqrt(discriminant);

     double x1 = b - discriminant;
     double x2 = b + discriminant;

     if(x2 < 0)
     {
          std::cout<<"x2"<<std::endl;
          return false;
     }
     if(x1 < 0)
     {
           x1 = 0;
           return true;
     }

     return true;
}

It is within the sphere class. The convertion between window and OGL coords:

Vector3d MouseClass::ConvertMouseToOGLCoordinate(int mouseX, int mouseY, int mouseZ)
{
    GLint viewport[4];
    GLdouble modelMatrix[16];
    GLdouble projectionMatrix[16];

    glGetIntegerv(GL_VIEWPORT, viewport);
    glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
    glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);

    //float winZ;
    float winY = float(viewport[3] - mouseY);
    //glReadPixels(mouseX, (int)winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

    double x, y, z;
    gluUnProject((double)mouseX, winY, mouseZ,
        modelMatrix, projectionMatrix, viewport,
        &x, &y, &z);

    return Vector3d(x, y, z);
}

And the function which checks whether the left mouse btn is clicked and if it is checks for the collision:

void HandleMouse()
{
    if(userMouse.IsLeftButtonDown())
    {
        int cursorX = int(userMouse.GetCurrentPosition().GetX());
        int cursorY = int(userMouse.GetCurrentPosition().GetY());

        Vector3d nearPoint = MouseClass::ConvertMouseToOGLCoordinate(cursorX, cursorY, 0.0f);
        Vector3d farPoint = MouseClass::ConvertMouseToOGLCoordinate(cursorX, cursorY, 1.0f);

        Vector3d direction = farPoint - nearPoint;
        direction.Normalize();

        positionInWorld = farPoint;

        mouseRay = Ray(nearPoint, direction);
        drawCube = true;
        for(int i = 0; i < 3; i++)
        {
            bool isCollided = sphere[i].CheckRayCollision(mouseRay);
            if(isCollided)
            {
                sphere[i].SetColor(0.0f, 1.0f, 0.0f);
            }
            else
            {
                sphere[i].SetColor(1.0f, 0.0f, 0.0f);
            }
        }
     }
}

The 'drawCube' bool var is just for me to show if the convertion func works well and the 'positionInWorld' var is for the cubes coords. The drawing is well, so I think the convertion function works, but I might've done sth wrong.

If anyone can help me sort out why isn't this code working I would be very gratefull! I have been struggling with this for a week and searched everywhere on the Internet and haven't found a solution yet...

Thanks in advance!

EDIT:

The picking isn't working here. Pressing the left mouse button doesn't select anything. No matter where I click...


texts: Unity 2d Animation from spritesheet: How can I move the character according to the animation?

texts:
I am trying to implement an attack animation that should end up in moving the player by some distance.
The animation would be something like this:

As you can see the position of the player should be different by the end of the animation, but I am not sure how to make it so. I tried to use root motion, however even if in the animator component i set "Apply root motion" to true, when I click on the animation itself, there is no option to use root motion, perhaps is it due to the fact that the animation is obtained from a spritesheet and not from a rigging software like Spine or DragonBones?
Anyway, is there another way to update, either by scripting or throught the animation window, the character's position after the animation?


texts: Render just the pixel under mouse cursor in DirectX

texts:
I'm having difficulties rendering just a single pixel which is on the defined coords of viewport. I'm using D3DXMatrixPerspectiveOffCenter function, but the result is not what I expected.

Here is how I calculate the parameters for the function:

// pCamera is the actual camera used to render full screen picture

// what is the width and height of camera near plane in Camera Space
double dHeight = 2 * pCamera->m_dNear * (tan(pCamera->m_dFOVy/2.0));
double dWidth  = dHeight * pCamera->m_dRatioXY;

// what is the pixel size in Camera space
double dHeightReduced = (dHeight / pCamera->m_dViewportHeight) * CAMERA_1x1px_SIZE;
double dWidthReduced = (dWidth / pCamera->m_dViewportWidth) * CAMERA_1x1px_SIZE;

// mouse pixel position in Camera space
double dCamSpaceX = -0.5*dWidth  + double(uiMousePosX) / pCamera->m_dViewportWidth    * dWidth;
double dCamSpaceY = -0.5*dHeight + double(uiMousePosY) / pCamera->m_dViewportHeight   * dHeight;

// create matrix
D3DXMatrixPerspectiveOffCenterRH( &m_mProjection,
         (float)(dCamSpaceX),
         (float)(dCamSpaceX+dWidthReduced),
         (float)(dCamSpaceY),
         (float)(dCamSpaceY+dHeightReduced),
         (float)m_dNear,
         (float)m_dFar );

(I set CAMERA_1x1px_SIZE = 100 to see a part of the scene, but I see the scene distorted and it's definitely NOT just the cut-off of the original)

How do I need to calc the params to make it work?

Thanks.


texts: How can I get a list of servers hosted by my players?

texts:
I'm writing a multiplayer 2D online game, where game servers are hosted by the players. I want to show players a list of the currently hosted game servers.

How would I do that? I know how to let players host servers. But how would I then get a server list? Should I use a database? Is there an easier way?


texts: Networking with UDP, should I keep sockets open on the server

texts:
I am working on making a 2D platforming game that will have multiplayer functionality. Over the last few days, I have done a lot of reading regarding how to deal with the networking, and believe that I am on the way to implementing some of the concepts I have read about.

I have decided to go with an Authoritative server/client model, where multiple clients will send actions made by the user to the server, client will predict the players next steps before comparing against the Authoritative reply from the server, etc. This seems to have been suggested in numerous corners of the web regarding games networking, and seems reasonable.

Before jumping straight into trying to get snapshots sent from the server, I wanted to make sure that I had an idea of some of the technical nuances of a language, as conceptual knowledge can only get me so far. I have set up a simple Echo Server that has worked rather well for a single client, but now my next step is to have multiple clients connected to the server at a single moment, and have each message that is sent from a client echoed to all clients connected to the server.

I feel that the answer might be language dependent, so I will mention now that currently I am using Java for the networking (a little bit of preliminary testing may suggest that Java has significant overhead in its network implementation, so I am open to change upon suggestion). I am using UDP for speed sake (and this seems to be what is predominantly suggested).

My question is with the server, should I be keeping each DatagramSocket that represents a connected client open and send DatagramPackets directly out without ever closing them (until the program terminates, client disconnects, etc.), and have them stored in some form of Collection, or should I close them after each message is sent and create a new outgoing socket whenever I need to send a packet? There are obvious performance disadvantages of creating a  socket whenever I need to send a message, but is there some fundamental reason that I have not come across that suggests leaving sockets open is not a good idea?


texts: GLSL Shader - Change Hue/Saturation/Brightness

texts:
I'm trying to change the hue of an image using a GLSL fragment shader. I want to achieve something similar to Photoshop's Hue/Saturation Adjustment layer.

In the following image you can see what I've got so far. I want to change the hue of the green square so it looks like the red square on the right, but with this shader I get a half red half pink square (the square in the middle).

What I'm doing in the fragment shader is converting the texture's color to HSV, then I add the HSV color that I get from the vertex shader to it and I convert the color back to RGB.
What am I doing wrong?

Fragment shader:

precision mediump float;
varying vec2 vTextureCoord;
varying vec3 vHSV;
uniform sampler2D sTexture;

vec3 convertRGBtoHSV(vec3 rgbColor) {
    float r = rgbColor[0];
    float g = rgbColor[1];
    float b = rgbColor[2];
    float colorMax = max(max(r,g), b);
    float colorMin = min(min(r,g), b);
    float delta = colorMax - colorMin;
    float h = 0.0;
    float s = 0.0;
    float v = colorMax;
    vec3 hsv = vec3(0.0);
    if (colorMax != 0.0) {
      s = (colorMax - colorMin ) / colorMax;
    }
    if (delta != 0.0) {
        if (r == colorMax) {
            h = (g - b) / delta;
        } else if (g == colorMax) {
            h = 2.0 + (b - r) / delta;
        } else {
            h = 4.0 + (r - g) / delta;
        }
        h *= 60.0;
        if (h < 0.0) {
            h += 360.0;
        }
    }
    hsv[0] = h;
    hsv[1] = s;
    hsv[2] = v;
    return hsv;
}
vec3 convertHSVtoRGB(vec3 hsvColor) {
    float h = hsvColor.x;
    float s = hsvColor.y;
    float v = hsvColor.z;
    if (s == 0.0) {
        return vec3(v, v, v);
    }
    if (h == 360.0) {
        h = 0.0;
    }
    int hi = int(h);
    float f = h - float(hi);
    float p = v * (1.0 - s);
    float q = v * (1.0 - (s * f));
    float t = v * (1.0 - (s * (1.0 - f)));
    vec3 rgb;
    if (hi == 0) {
        rgb = vec3(v, t, p);
    } else if (hi == 1) {
        rgb = vec3(q, v, p);
    } else if (hi == 2) {
        rgb = vec3(p, v, t);
    } if(hi == 3) {
        rgb = vec3(p, q, v);
    } else if (hi == 4) {
        rgb = vec3(t, p, v);
    } else {
        rgb = vec3(v, p, q);
    }
    return rgb;
}
void main() {
    vec4 textureColor = texture2D(sTexture, vTextureCoord);
    vec3 fragRGB = textureColor.rgb;
    vec3 fragHSV = convertRGBtoHSV(fragRGB);
    fragHSV += vHSV;
    fragHSV.x = mod(fragHSV.x, 360.0);
    fragHSV.y = mod(fragHSV.y, 1.0);
    fragHSV.z = mod(fragHSV.z, 1.0);
    fragRGB = convertHSVtoRGB(fragHSV);
    gl_FragColor = vec4(convertHSVtoRGB(fragHSV), textureColor.w);
}

EDIT:
Using the functions Sam Hocevar provided in his answer, the problem with pink bands is solved, but I can only reach half of the color spectrum. I can change the hue from red to green, but I can't change it to blue or pink.

In the fragment shader, I'm doing this now:

void main() {
    vec4 textureColor = texture2D(sTexture, vTextureCoord);
    vec3 fragRGB = textureColor.rgb;
    vec3 fragHSV = rgb2hsv(fragRGB);
    float h = vHSV.x / 360.0;
    fragHSV.x *= h;
    fragHSV.yz *= vHSV.yz;
    fragHSV.x = mod(fragHSV.x, 1.0);
    fragHSV.y = mod(fragHSV.y, 1.0);
    fragHSV.z = mod(fragHSV.z, 1.0);
    fragRGB = hsv2rgb(fragHSV);
    gl_FragColor = vec4(hsv2rgb(fragHSV), textureColor.w);
}


texts: Unity Player Movement Script nullifies gravity

texts:
i want my Player to be affected by gravity, while being able to be moved in horizontal direction(the Player jumps up and down), but my script:

Vector3 move = new Vector3(Input.GetAxis("Horizontal"), (Input.GetAxis("Vertical")), 0);

transform.position += move * speed * Time.deltaTime;

...seems to nullifiy gravity. Can someone tell me how to fix that?


texts:
I'm a programmer but have not yet developed any games.

I have played various 3D games and always wondered how the Map of the field is stored and rendered.

I know some acceleration card is a necessary hardware, but how exactly the view is changed without even a single flicker on the screen.

Do you have any online material to help me understand this.

Thanks


texts: Unity 5 - Audio Source - 3D rolloff without stereo pan effects

texts:
Somebody know if it is possible to use 3D rolloff of of an Audio Source without having stereo effects (You get a stereo pan effect depending on the position of your audio listener).

I know that I can do Spatial Beld to 2D but then the 3D rolloff stops and I would have to implement my own rolloff.


texts: How do you prevent your JavaScript / HTML5 web game from being copied or altered?

texts:
I'm in the middle of planning a game built using JavaScript and HTML5.

I'm having trouble understanding how you could prevent someone from simply copying the JavaScript from the web server and either making their own game with it (not my biggest concern), or substituting their own JavaScript functions and dashing any hope for reliable clients in the wild if the game was to eventually support multiplayer.

Can anything be done to prevent just anybody from reading the JavaScript?

If not, should all game processing be taking place on a server somewhere with the client's only responsibilities being capturing user input and drawing graphics?


texts:
My game runs smooth when I deploy it to my windows phone directly from Visual Studio 2012 in debugging mode.

But when I sideload/deploy the same .xap file with the Application Deployment Tool, the game runs much worse.

Why is that happening?


texts:
I did not find a question on these lines yet, correct me if I'm wrong.

Trees (and fauna in general) are common in games. Due to their nature, they are a good candidate for procedural generation.

There's SpeedTree, of course, if you can afford it; as far as I can tell, it doesn't provide the possibility of generating your tree meshes at runtime. Then there's SnappyTree, an online webgl based tree generator based on the proctree.js which is some ~500 lines of javascript.

One could use either of above (or some other tree generator I haven't stumbled upon) to create a few dozen tree meshes beforehand - or model them from scratch in a 3d modeller - and then randomly mirror/scale them for a few more variants..

But I'd rather have a free, linkable tree mesh generator.

Possible solutions:

Port proctree.js to c++ and deal with the open source license (doesn't seem to be gpl, so could be doable; the author may also be willing to co-operate to make the license even more free).
Roll my own based on L-systems.
Don't bother, just use offline generated trees.
Use some other method I haven't found yet.

Update 2015: ended up porting proctree.js to c++ https://github.com/jarikomppa/proctree


texts: How to code simple Goomba-like AI for 3D Platformer?

texts: I'm making a 3D Platformer and have an enemy similar to a Goomba in terms of AI. How do I get the enemy to walk around and then follow the player when they're in range?


texts: Movement & Physics in an entity-component system

texts:
I'm currently playing around with entity-components systems and got started on the movement/collision/physics parts and would like to have some pointers!

It's a basic 2D sidescrolling game, with the goal being something in the style of Terraria. My first goal was to have a character that could run left/right & jump on blocks/tiles and when clicking tiles they'd disappear.

At the moment, each tile/block on the screen is an entity with a Transform(Position) component, a "Renderable component and a Collision component (boundaries)

My player has a Player component(tagging class), a Transform, Renderable, and Physics (velocity, acceleration, mass) and Collision component.

Currently a bit stuck on how to fit in the physics and movement. I read the threads I could find about it here on Stack but left with some questions:

What would be a good approach to let my character move? Should I have a player system that updates the Player's position or velocity? Or should I let it set a state & let another system update the movements of entities based on their velocities and their current state? Leaving the option open that I could move a character by clicking somewhere?
If I were to add gravity, should these affect your acceleration/velocity? I have problems with figuring out how to implement acceleration & which systems could/should be responsible for that..

And unrelated to the questions above, when I was starting on the collision I ran into the issue that it would try to check every single tile against the player & since on a large resolution already 1000ish entities fill the screen it quickly sent performance down the drain. I implemented a quad tree to select the entities only around the player, which seems to work. (Based on http://www.mikechambers.com/blog/2011/03/21/javascript-quadtree-implementation/ but made it from scratch in Python).

But since it takes the current window size as dimensions once the player would move off screen,  the entities wouldn't add correctly anymore. Should I let the Quad Tree grow/shrink in certain directions? (If anyone has experience with using this?)

Thanks in advance!


texts: changing body type without change of center of mass

texts:
I have an box2d project with some bodies in it, which move around without any user interaction. But if the user selects one of the bodies, he should be able to move it around just like he wants to.

To keep it short, I want to change the type of the body to "kinematic" while the user controls it and back to "dynamic" afterwards. If I do so the rotation center of the body changes with the change of the type. How can I reset this?

The body's fixture is created of a single b2PolygonShape, with its vertices set via SetAsArray().

Greetings philipp

EDIT::

So I looked around about setting the local center of bodies. what brought me to this solution:

var md = new b2MassData();
this.body.GetMassData( md );
this.body.SetType( b2body.b2_kinematicBody );
this.body.SetMassData( md );

that did not work, so I had a look at the source and found that SetMassData() always returns if the body is not "dynamic".

So I tried this:

var md = new b2MassData();
this._body.GetMassData( md );
this._body.SetType( b2Body.b2_kinematicBody );
this._body.m_sweep.localCenter.Set( md.center.x, md.center.y );

what actually is modifying the private data of the body. But it works and no errors appear, but can I really do this without the risk of breaking the application, or in other words, under which circumstances could this solution might cause errors?

n.b.:
I am using box2dweb of the latest release.

Greetings philipp


texts: Multiplication for MVP matrices: Any benefits to doing so within the vertex shader?

texts:
I'd like to understand under what circumstances (if any) it is worth doing MVP matrix multiplication inside a vertex shader.

The vertex shader is run once per vertex, and a single mesh typically contains many vertices. All MVP inputs remain the same for each vertex in the vertex batch relating to a given draw call (model). Surely then, you're always better off keeping the multiplications in the client code, such that you pass in the whole MVP precalculated as a uniform? (avoiding redundant ops between individual vertices)


texts: textures in tilemap games: use 2d planes or 3d objects? (example with Dragons of Atlantis)

texts:
How to create the textures in games such as Dragons of Atlantis?

I was thinking about 2 ways:

using 2d planes to save space and memory, using the color from the 3d
software
adding a very simple mesh and stick a detailed texture onto it in Unity

Is there a preferable way to choose between the two?
The first solution could save some memory, but maybe a bit difficult to change the camera view for example at the end of the game.
As for the second solution, it would be creating a very detailed mesh in the 3d software, paint the texture, cut the texture and add it to a very simple mesh, such as cubes. Could be better, but maybe it would take more work.

What do you think?

Thanks


texts: Engine for a Football Manager Type game (data driven, menu clicking)

texts:
A friend and I had started developing a football manager two years ago, but ultimately squashed the whole thing because we found ourselves in a mess with developing UI and saving/loading.
The basic game loop of simulating matches and advancing days until the match day was already done. We also had a e-mail system up and running (for receiving messages which might need decisions/trigger events).
In our lack of of knowledge, we tried building the game in GameMaker2. It made saving all the objects (a Team has 23 Player, a league has 20 Teams, there are several Leagues) a nightmare. Also, UI development (things like scrollbars for example) ate up incredible amounts of our time and still everything looked relatively bland. Short: GameMaker2 seemed not suitable for the type of game we wanted to build.
There must be a better engine/system for developing a manager type game. Most of the game is spent in menus, There's no time-critical interaction going on.
Since we've benched the project, I started working a legit software development job and I have gained some skills which I hadn't have before, like knowledge of databases and a heap of Python experience.

It has me looking at the game again. Now I see it as having a 'data backend' and an point-and-click-frontend, with game design elements, like tough decisions, events and goals as the driving force in the middle.
We want nice looking menus, where players can set the training schedule, make the line-up for match day, talk to players/executives/whoever. The other necessity is managing all data objects, which there will a lot of. A league might easily contain 400 players which all need to have stats and so on and so forth. I see a relational database for this, but maybe there's something smarter regarding game-development?

So my Question is:

What is a suitable game engine/development stack for developing data-heavy, non real-time menu-clicking type manager games  such as a football manager?


texts: Vulkan - preallocating chunks of memory and resource memory requirements

texts: I would like to allocate a bigger chunk of memory and then suballocate from it but I don't fully understand how memory requirements work, is there a chance that when I allocate a piece of device local memory there might be some buffer/texture that memory requirements of which will not include this heap? Or is it safe to assume that if it's a device local heap it will always be viable for device local resources?


texts: Is it ok to use copyrighted assets for educational purposes?

texts:
A friend and I were wanting to create a Pokemon battle simulator in our mobile development class as our final project but are worried whether or not it would be permissible under "Fair Use" for educational purposes. We have no plans on doing anything with the game after the class and our presentation of the app, we just wanted to try to clone some very basic parts of it onto Android.

Edit: I'm located in the US.


texts: How to modify a property after animating it in Unity3D?

texts:
I animate localPosition. The animation works well, but after, I can't change a value of localPosition in editor or code. I want to change a value after the animation completes, not at the same time.

I use Animator with AnimationClipPlayable. I create Animator in editor and the rest in code (AnimationClip, AnimationClipPlayable, AnimationCurve).

The animation animates a property from one position to another. It finishes, I don't do anything to stop the animation.

Let me know, if you need a code example or video presentation.


texts: Get world coordinate under mouse (at a ground plane for Warcraft 3 like movement)

texts:
I want to let a unit follow the mouse like in any RTS (Warcraft 3, Starcraft, ...). For that I have a "ground plane" which is defined through 2 vectors, the X and Z axis. Now I need to get the world coordinate of the mouse click on this plane in order to move the unit. I'm using OGRE & C++.

How can I get the coordinates of the mouse click on the ground plane?


texts: How to put basic scripting/variable changes into dialog xml files?

texts:
I have a simple XML structure for my dialog between the player and NPCs.
What I'd like to do is put variable changes (and maybe other things) directly into the XML.  So, for instance, if you select a certain conversation option the character gives you gold.  Like this:

<story>
  <segment id ="1">
    <dialog>
      <speaker>Fred</speaker>
      <text>Do you like futurecrew?</text>
    </dialog>
    <choice>
      <prompt>Yes</prompt>
      <target>2</target>
      <command>$gold-10</command>
    </choice>
    <choice>
      <prompt>No</prompt>
      <target>3</target>
      <command>$relationship-20</command>
    </choice>
  </segment>
</story>

In exploring this issue I have written a really terrible brute force command parser, but it just feels wrong at so many levels:

public class Command
    {
        string commandText;
        Symbol symbol;
        Field field;

        public Command(string _commandText)
        {
            commandText = _commandText;
        }

        public void Execute()
        {

            //look for operators
            int test = -1;
            int location = -1;
            int amount = 0;

            test = commandText.IndexOf("-");
            if (test != -1)
            {
                symbol = Symbol.Minus;
                location = test;
            }
            test = commandText.IndexOf("+");
            if (test != -1)
            {
                symbol = Symbol.Plus;
                location = test;
            }
            test = commandText.IndexOf("*");
            if (test != -1)
            {
                symbol = Symbol.Multiply;
                location = test;
            }
            test = commandText.IndexOf("/");
            if (test != -1)
            {
                symbol = Symbol.Divide;
                location = test;
            }
            string variable = commandText.Substring(0, location);
            amount = Int32.Parse(commandText.Substring(location + 1));

            if (variable.ToUpper() == "$GOLD")
                field = Field.Gold;

            if (field == Field.Gold)
            {
                Logger.log("Gold before {0}", Game.Instance.Gold);

                if (symbol == Symbol.Minus)
                    Game.Instance.Gold -= amount;
                if (symbol == Symbol.Plus)
                    Game.Instance.Gold += amount;

                Logger.log("Gold after {0}", Game.Instance.Gold);
            }
        }
    }

If I have 30 different variables I want to "expose" to the XML "scripting" it looks like I'll be writing a lot of stupid achey breaky code.

I have searched around and found people asking/answering about conditions, which I see as  simpler than this.  I have also seen suggestions for CodeDom for realtime compiling but this is in unity C# so I don't anticipate that will work.  I looked into LUA for .NET and IronPython but that seems overkill when really I just want the ability to change variables on my Game singleton.

Any ideas or direction would be much appreciated!

EDIT: I found UniLua https://github.com/xebecnan/UniLua for a unity safe pure c# implementation of lua.  I haven't decided yet if I'll use it, but my presupposition that I couldn't use Lua turned out to be false.


texts: What is the best way to funnel input to the correct entities?

texts:
I have an input pipeline that stores InputObjects into a queue, which I then iterate through once every frame.

while(!inputQueue.isEmpty())
{
    InputObject inp = inputQueue.pop();

    boolean handled = false;
    for(Entity entity : inputRecievingEntities)
    {
          //entity.manage() returns true if it wants to consume the event, false otherwise
          handled = entity.manage(input);
          if(handled)
               break;
    }
}

This works fine to make sure the input is handled by only one entity. However, consider this situation:

There is a button overlaying the screen. The user can either click the button to jump or press anywhere (else) on the screen to shoot in that direction (which is handled by the player entity). If the player entity happens to be before the button entity in the inputReceivingEntities list, the player will shoot and not jump. If the button is before the player, the player will jump, and not shoot (which would be correct). Obviously I could assign some sort of priorities to the objects and sort the list but is there a better way to do this?


texts: Multiple image objects extracted from spritesheets or one-two object for all?

texts:
Let's say I want to make a 2D game and I'll use a spritesheet containing all of the animation frames and a texture-atlas for static sprites such as walls, non-animated decorations...etc.

Should I create separate image objects for all the static sprites and for all animation-rows or should I just pass the on-texture-atlas (or on-spritesheet) coordinates for them?

Which solution, or "direction" is considered elegant in game-development?

Thanks for the help! :)

Some pseudocode:

Separate image objects:

Class StaticSprite {
  Image texture;

  // ...

  public Image getImage() {
     // ...
  }

  public static final CheckedWall cw = new CheckedWall( -- checked wall grid extracted from the texture-atlas -- )
  public static final WoodWall ww = new WoodWall( -- wood wall grid extracted from the texture...
}

Or:

class StaticSprite {
 int texX, texY, size;

 // ...

 public Image getImage() {
    // gives the part of the spritesheet
 }

 public static final WoodWall ww = new WoodWall( -- coordinates for the texture-atlas -- )
}

Assuming that the spritesheet is accessible for all these sprite-related classes.


texts:
I am trying to simulate a buoyancy force for objects submerged/suspended in a fluid in a 2D environment.

According to Game Physics: Engine Development: How to Build a Robust Commercial-Grade Physics Engine for Your Game by Ian Millington (Chapter 6, page 99) (ISBN 987-0-12-381976-5) AND the wikipedia article on buoyancy the actual calculation is: PVG where P is the density of the fluid. V is the submerged volume (area) and G is the gravitational acceleration (0.00980665 Kilo-Newtons for Earth, but is variable in the code) and always acts in the opposite direction to gravity.

The code I have, below, produces a clean-looking result, but obviously the density of either the object in question or the fluid is not effecting the calculation, only the mass. If I insert the density of the fluid, say, water, at 1000.0 kg/m^3 the whole system explodes.

Is it something simple that I missed or did I screw up entirely?

The code I have so far:

//area_ratio is a scalar ratio of the area inside the defined fluid area (Volume submerged) and the entire object's bounding area (entire volume).
//area_ratio is equal to a value in the interval [0.0, 1.0]
//gravity is a force vector in Kilo-Newtons.
Vector2D current_weight(mass * area_ratio * gravity);

//current_area = The area inside the fluid. (Volume submerged)
Vector2D buoyancy(gravity.Normalize() * -current_weight * current_area);

//Forces and Impulses are automatically converted to Netwons by multiplying the values passed in by 1000.0
object->ApplyImpulse(buoyancy);


texts: Making a border around a translucent shape in LibGdx

texts:
The recommended method for making a border around a shape using LibGdx is to draw a larger version of the shape to serve as the border, then draw the shape over the larger image.

shapeRenderer.setColor(borderColor);
shapeRenderer.circle(x, y, radius + borderWidth);
shapeRenderer.setColor(shapeColor);
shapeRenderer.circle(x, y, radius);

This works well most of the time, but if you want shapeColor to have any opacity less than 1, it fails.  The problem is that you can see the borderColor through the shape, and the colors are blended.

Is there anyway to fix this issue?


texts: Child transforms problem when loading 3DS models using assimp

texts:
I'm trying to load a textured 3d model into my scene using assimp model loader.

The problem is that child meshes are not situated correctly (they don't have the correct transformations).

In brief: all the mTansform matrices are identity matrices, why would that be?

I'm using this code to render the model:

void recursive_render (const struct aiScene *sc, const struct aiNode* nd, float scale)
{
    unsigned int i;
    unsigned int n=0, t;
    aiMatrix4x4 m = nd->mTransformation;

    m.Scaling(aiVector3D(scale, scale, scale), m);

    // update transform
    m.Transpose();
    glPushMatrix();
    glMultMatrixf((float*)&m);

    // draw all meshes assigned to this node
    for (; n < nd->mNumMeshes; ++n)
    {
        const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];
        apply_material(sc->mMaterials[mesh->mMaterialIndex]);

        if (mesh->HasBones()){
            printf("model has bones");
            abort();
        }

        if(mesh->mNormals == NULL)
        {
            glDisable(GL_LIGHTING);
        }
        else
        {
            glEnable(GL_LIGHTING);
        }

        if(mesh->mColors[0] != NULL)
        {
            glEnable(GL_COLOR_MATERIAL);
        }
        else
        {
            glDisable(GL_COLOR_MATERIAL);
        }

        for (t = 0; t < mesh->mNumFaces; ++t) {
            const struct aiFace* face = &mesh->mFaces[t];
            GLenum face_mode;

            switch(face->mNumIndices)
            {
                case 1: face_mode = GL_POINTS; break;
                case 2: face_mode = GL_LINES; break;
                case 3: face_mode = GL_TRIANGLES; break;
                default: face_mode = GL_POLYGON; break;
            }

            glBegin(face_mode);

            for(i = 0; i < face->mNumIndices; i++)// go through all vertices in face
            {
                 int vertexIndex = face->mIndices[i];// get group index for current index
                 if(mesh->mColors[0] != NULL)
                     Color4f(&mesh->mColors[0][vertexIndex]);
                 if(mesh->mNormals != NULL)
                     if(mesh->HasTextureCoords(0))//HasTextureCoords(texture_coordinates_set)
                     {
                         glTexCoord2f(mesh->mTextureCoords[0][vertexIndex].x, 1 - mesh->mTextureCoords[0][vertexIndex].y); //mTextureCoords[channel][vertex]
                     }
                     glNormal3fv(&mesh->mNormals[vertexIndex].x);
                     glVertex3fv(&mesh->mVertices[vertexIndex].x);
             }
             glEnd();
        }
    }
    // draw all children
    for (n = 0; n < nd->mNumChildren; ++n)
    {
         recursive_render(sc, nd->mChildren[n], scale);
    }
    glPopMatrix();
}

What's the problem in my code ?

I've added some code to abort the program if there's any bone in the meshes, but the program doesn't abort, this means : no bones, is that normal?

if (mesh->HasBones()){
    printf("model has bones");
    abort();
}

Note: I am using openGL & SFML & assimp


texts: Slick2D: Animation not being parsed from spritesheet correctly

texts:
I have a 960x960 spritesheet with each tile being 192x192.  I initialized my spritesheet and animation like so:

spritesheet = new SpriteSheet("resources/spritesheets/player.png", 192, 192);
walkingLeft = new Animation(spritesheet, 3, 0, 0, 1, true, 20, true);

When I attempt to render the animation, I get a java.lang.ArrayIndexOutOfBoundsException: -1 error.  This error doesn't occur when I'm creating an animation from images in the same row.  Therefore, I'm assuming that the error is being caused because of the way Slick is handling horizontal scanning (going to the next row after reaching the end).


texts: What is a faster alternative to a GetComponent from a RaycastHit?

texts:
I have a basic AI car script which needs to interact with other cars around it. I would like to access variables from the other cars to help one car identify what the other cars are doing so they can avoid jams and crashes better.

One way to do this would be a raycasthit (ignore any errors there, you know what I mean):

if(Physics.Raycast(...))
{
    hitCar = hit.transform.gameObject.GetComponent<Car>();
}

However, I know that GetComponent can be very performance taxing especially if it's done every time there's an intersection with the raycast.

Another way would be to save all of the cars in an array or list before hand, and then test the name of it against all the names in the array or list.

if(Physics.Raycast(...))
{
    for(int i = 0; i < listOfCars.length; i++)
    {
        if(carName == listOfCars[i].name)
        {
            hitCar = listOfCars[i];
        }
    }
}

However, I've heard that string comparisons (again, especially if there's a lot of intersections with the raycast) can also be taxing on performance.

What's the best way to do this?


texts: Is it a good idea to make most actions in a game driven by simple tiny threads (in Java)?

texts: I'm thinking of for example making the jump action of a character, that takes ~1s, a distinct runnable, so then other threads can read its state, with additional control over the action itself by the "action thread". Are people doing this? What is there to consider when thinking about creating and destroying hundreds (or thousends) of threads a second in a bigger game or other application?


texts: Octree contains tris, shapes, models or both?

texts:
Right now, each node of my octree contains a list<Triangle*> (pointers to mesh triangles).

So basically an octree query returns poly soup.

Sometimes I want to query the octree for entire objects however.  Each Tri has a pointer to its "owner object", but should I park the object references in the same octree (ie give each node a list<GameObject*> or maintain a completely different octree altogether?


texts: Can you use well known buildings in your game?

texts:
Is it legal to reference a real city in your game and use the same architecture of well known shops and buildings?

For example, I'm sure you can't create an exact 3D model of McDonalds, put it in your game, and sell it. However, is it possible to use the same architecture, but different name? and even use the same colors, just as long as the name and logos are not used?
Or would there be the possibility of getting in trouble for creating something in the "likeness".


texts: Large gap between the grabbed game object and controller

texts:
When i grab a gameobject, there is a gap between them. I have tried changing the scale of the colliders, tool handle position from global to pivot but nothing worked for me. Should i reset the pivot points of model in 3D modeller and reimport it again or is there another way to solve this?

I have attached few screenshot related to the problem


texts: Is Gresham's Law relevant for modern online games that allow the use of real money as additional currency?

texts:
More and more online games are planning to allow the use of real money to purchase ingame items in addition to the standard ingame currency. Diablo III for example, which will be released next year, will feature a gold-auction house (only ingame gold allowed) and a real money auction house (only real money allowed) to trade items between players inside the game.

Gresham's Law says that: "When government compulsorily overvalues one money and undervalues another, the undervalued money will leave the country or disappear from circulation into hoards, while the overvalued money will flood into circulation."

People are worried that ingame gold will be severely undervalued and real money will be dominating because the developers of the game get their share from real money transactions and want to push this currency. They are the government that might compulsorily overvalue real money and undervalue ingame-gold. This means according to Gresham's Law that we will see the ingame currency gold vanish over time, leaving the real money auction house as the only option to buy and sell items.

This leads to the question, if Gresham's Law can be applied to this scenario. What are the reasons why or why not Gresham's Law will effect online games with real money and virtual currencies combined in the same market.


texts: Tilemap layer scaling and Camera issue in Phaser

texts:
I'm working with the Phaser framework and I'm struggling with a camera/rendering issue when scaling a tilemap layer to simulate a zoom feature in my project.

The camera size is set to 1024x768px.(Same as the stage size)
I then create a tilemap and a tilemap layer that is 3072x2304px.

    // Create the tilemap and the tilelayer
    this.map = this.add.tilemap();
    this.map.addTilesetImage('tiles');

    this.layer1 = this.map.create('layer', 96, 72, 32, 32);
    this.layer1.resizeWorld();

Code to zoom

        this.layerScaleGroup = this.add.group();
        this.layerScaleGroup.add(this.layer1);
        this.layerScaleGroup.add(this.marker);

        this.layerScale = 1;
        this.inputScale = 1;

In the update function

        if(this.input.keyboard.isDown(Phaser.Keyboard.Q)){

            this.layerScale -= .2;
            this.inputScale += .2;

        }
        if(this.input.keyboard.isDown(Phaser.Keyboard.A)){

            this.layerScale += .2;
            this.inputScale -= .2;

        }

        this.layerScale = Phaser.Math.clamp(this.layerScale, .33, 1);
        this.inputScale = Phaser.Math.clamp(this.inputScale, 1, 3);

        this.layerScaleGroup.scale.set(this.layerScale);
        this.input.scale.set(this.inputScale);

When completely zoomed out I need the tilemap layer to be shown in the camera, but instead it seems like the camera or a camera follows the scale of the tilemap layer, even though the original camera is still 1024x768.

Here is a video showing the issue.
https://youtu.be/e2mRfigq98I

When you are zoomed out you can still draw a tile onto the tilemap, but it is not rendered.


texts:
I am working on a brick breaker style game (i.e., like Arkanoid) in C#/XNA. As I add more features such as powerups, special brick types, etc I am running into problems figuring out how the whole game should be structured. For instance, I have a static CollisionManager class that my ball objects call each update to check if they are hitting something like a brick. While this works, it also puts the ball object in charge of updating other objects (such as letting the Brick know it has been hit, or some other game function not directly related to the ball).

Every powerup or feature I add keeps forcing me to re-evaluate how everything is pieced together. Are there any types of standard layouts I could use to help minimize problems like this? I like the idea of having my CollisionManager just manage collisions, and my ball objects just managing stuff related to the ball, and bricks managing brick stuff; however, some cases require updating multiple things. This leaves me trying to figure out just which part of my app I should put in charge of the dirty work of handling these specialized tasks.


texts: most efficient Bounding Sphere vs Ray collision algorithms

texts:
Is there a known 'most efficient' algorithm for Sphere vs Ray collision detection?

I recently stumbled accross Arvo's AABB vs Sphere collision algorithm, and I am wondering if there is a similarly noteworthy algorithm for this.

One must have condition for this algorithms is that I need to have the option of querying the result for the distance from the ray's origin to the point of collision. Although if there is another, faster algorithm which does not return distance, then in addition to posting one that does, also posting that algorithm would be very helpful indeed.

Please also state what the function's return argument is, and how you use it to return distance or a 'no-collision' case. For example, does it have an out parameter for the distance as well as a bool return value? or does it simply return a float with the distance, vs a value of -1 for no collision?


texts:
I'm trying to draw a surface in black in Game Maker. This is the code:

//Create event
surf = surface_create(room_width, room_height);

//Draw event
surface_set_target(surf);
draw_clear_alpha(c_black, 0.8);
surface_reset_target();

It seems to only work when I minimize and then maximize the game. How can I make this work without having to minimize the game?


texts: When updating to Universal Render Pipeline an Error occurs

texts:
I updated to the Universal Render Pipeline and despite of using the auto upgrade from project an error messages appears in the console. Here is the error:
In order to call GetTransformInfoExpectUpToDate,
RendererUpdateManager.UpdateAll must be called first.
UnityEngine.Rendering.RenderPipelineManager:DoRenderLoop_Internal(RenderPipelineAsset, IntPtr, AtomicSafetyHandle)


texts: Why would you use software rendering over hardware rendering, today?

texts:
As opposed to CPU or software rendering I assume?

Wouldn't generally all current rendering be GPU based, seeing as you would be using OpenGL or Direct X?

Could someone give me some info here, can't find any suitable answers?


texts: SDL Combining text and Geometry Rendering to one texture

texts:
Basically I'm trying to end up with a Texture class that can take in text and have it be drawn over simple geometry (such as a letter 'A' over a filled rectangle). However I'm running into issues when thinking about how to combine these two concepts.

First, following lazy foo's tutorials, Geometry rendering is simple and is done with an

SDL_RECT and SDL_RenderFillRect(SDL_Renderer*, &SDL_Rect);

However, when rendering text it uses Surfaces and Textures in order to 'draw' the text. Specifically these lines:

SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
mTexture = SDL_CreateTextureFromSurface( SDL_Renderer*, textSurface );

My confusing comes from trying to figure out several things:

a) Is it possible to maybe first Render the Geometry to a texture, and then render the text over that same texture?

b) I believe a call to  SDL_SetRenderTarget is going to be necessary, but I'm not sure where and when during my combination stage this would need to be done.

c) Right before posting this question, I saw further down on the tutorials this link which describes rendering geometry to a texture, however I'm still not sure how to combine Text with this.

Any help is appreciated, Thanks


texts: Is there a difference in the time taken to load one texture instead of many?

texts: Is there a difference in the loading time of 16 256*256 textures versus a single 1024*1024 texture? Specifically for level loading time?


texts: Is the standard collision detection in Slick2D too heavy for broadphase?

texts:
I was wondering two things about the built in shape detection of Slick2D. When executed on a lot of shapes, how performant are the intersects and containsmethods, and what kind of algorithm is behind those.

I have implemented SAT collision detection but I don't want to execute this detection on all my entities. So I thought I would use the built in methods to look for entries which are near my player, and for those do the SAT detection.

But if the built in methods are as good as or better than SAT, this wouldn't be good. Also if the built in methods need more time or are kind of heavy for the cpu.

What is the proper way to have my collision detection on the smallest amount of game objects. How would I filter only the near objects?


texts: How to mirror flip animation curves in Unity?

texts:
I have a animation that moves my camera from left to right. Now I'd like to copy it with 'mirror' transformation so I can use it to move from right to left.

Is it possible to do it using script or purely in editor?


texts: How do I determine which side of the player has collided with an object?

texts: I have some static bodies (platforms) and a dynamic body (the player) in my world. The collision between them works great, but I would like to know which side of the player (rectangle) collides with the platform. How do I get this information?


texts: What is missing from SDL for it to gain more widespread adoption?

texts:
As I understand, SDL offers abstractions that let you make windows, handle input and audio much easier than doing so directly with the low level APIs provided by several operating systems.

However, it seems that a lot of games, both indie and AAA, don't use it, and I would like to know why. This makes me suspect that there may be areas where SDL is lacking, such as features, performance, or robustness, when compared to platform-specific APIs.

Apart from platform support, that is, considering only the platforms SDL supports, I do not understand what would keep a developer from using SDL for their game, since I feel like, based on my admittedly limited knowledge, it'd be much smarter to use SDL on the platforms that do support it.


texts: Coordinates of the corners of a rectangle bridging two circles

texts:
I am implementing a game that involves slingshots and circular objects. I have gotten the basic "geometric" construction down for rendering the slingshot, but I am having trouble implementing this in my game (written in js, although any language explanations will be understood). Below is a diagram of the desired construction:

I know (cx, cy), which is the center of the circle I am "launching", the radius of that circle, and the position of the mouse at any given time (mx, my). The second circle around (mx, my) includes the same radius as the circle centered at (cx,cy). Lines ST and QP are parallel.

I must find the coordinates of points P, Q, S, and T. Any efficient approaches to this problem? (Would I use trigonometry, vector math, algebra?) Specific examples are appreciated. Thank you.


texts: XNA C# How to draw fonts in different color

texts:
I'm doing a simple chat system with XNA C#. It is a chatbox that contains 5 lines of chat typed by the users. Something like a MMORPG chatting system.

[User1name] says: Hi
[User2name] says: Hello
[User1name] says: What are you doing?
[User2name] says: I'm fine
[System] The time is now 1:03AM.

When the user pressed 'ENTER', the text he entered will be added inside an ArrayList

chatList.Add(s);

For displaying the text he entered, I used

for (int i = 0; i < chatList.Count(); i++)
{
spriteBatch.DrawString(font, chatList[i], new Vector2(40, arr1[i]), Color.Yellow);
}

*arr1[i] contains 5 y-axis points to print my 5 line of chats in the chatbox

Question1: What if I have another type of message which will be added into ChatList (something like a system message). I need the System Message to be printed out in red color.

And if the user keeps on chatting, the chat box will be updated according: (MAX 5 LINES) The newest chat will be shown below, and the oldest one will be deleted if they reached the max 5 lines.

[User2name] says: Hello
[User1name] says: What are you doing?
[User2name] says: I'm fine
[System] The time is now 1:03AM.
[User1name] says: Ok, great to hear that!

I'm having trouble to print each line color according to their msg type. For normal msg, it should be yellow. For system msg, it should be red.

Question2: And for the next problem, I need the chat texts to be white color, while the names of the user is yellow (like warcraft3 chat system). How do I do that?

I have a hard time thinking of a solution for these to work. Advise needed.


texts:
I'm currently reading this book and are at the chapter about the rendering subsystem of a game engine.

Now, the book suggests that a material is a structure that provides information on how to shade a mesh. So the material contains visual properties and also what information to send to the shader prior to rendering.

My question is: What is a good tructure/syntax of such a material model?

My current ideas are that the material holds info such as specularity, diffuse colors, textures and so on. The (to me) tricky part comes when a shader needs multiple render passes.

A simple material could be something a long the lines of:

Transform info:
ModelMatrix : get_from_model
ViewMAtrix: get_from_camera
ProjectionMatrix: get_from_camera

Textures:
diffuse: get_from_file
normalmap: get_from_file
glossmap: get_from_file

Lighting:
direction: get_from_somewhere
.
.
.

But for instance, if I want to render the reflection of a mirror,  need a good way to tell the engine that I want to render the scene with the camera flipped in the mirror plane, and perhaps with a lower LOD. Is there a well know good way to encode this in the interface between user-data and the shader program?

Also, in general, are there well proven methods for mapping in-game data to shaders without too much manual instruction on where to find the data?

Thanks in advance : )


texts: How to prevent OnCollisionEnter2D calling a function again and again?

texts:
My current code makes a ball keep jumping whenever it hits the ground. But when it hits a vertical ground it keeps calling the jump function again and again. That is because OnCollisionEnter2D makes the isGrounded bool true as long as it is in touch with a vertical collider. I tried several ways for example this didn't work for me:

void FixedUpdate()
{

    if(isGrounded == true){
    Verticaljump();
    isGrounded = false;
    }
}
void OnCollisionEnter2D(Collision2D collision) {
    if(collision.gameObject.CompareTag("H-Ground")){
        isGrounded = true;
    }
}

As shown in the picture the OncollisionEnter2D starts and keep adding force on y-axis.Is there any way I can call a function only once even if the gameObject keeps colliding with a surface.

OnCollisionExit2D also does not work. So how can I call a function only once as it collides with ground and even if it keeps colliding with the ground?


texts: Are there any benefits for using the CPU instead of the GPU?

texts: I've been researching processors and graphics cards, and I discovered that GPUs are way faster than CPUs. I read in this one article, a 2-year-old Nvidia GPU outperformed a 3.2GHz Core I7 Intel processor by 14 times in certain circumstances. If GPUs are that fast, why don't developers use them for every function in a game? Is it possible for GPUs to do anything other than graphics?


texts:
I am trying to reproduce the raycasting of the game Wolf3D. I read this tutorial, but I am struggling to understand how to code the intersection between the rays and the walls by using angles and pixels.

I have coded something but my approach to the concept seems quite wrong:

void    ray_cast(t_wolf3d *w)
{
    int         wall_hit; // tell us if a ray hits a wall so we can stop the algorithm
    t_ray       ray;    // add the ray if we don't hit a wall
    double      angle_s; // will be a part of the FOV (subsequent column)
    int         rayAdvance = 0;

    int         x; // for each pixels ont the screen

    angle_s = 0.0;
    x = -1;
    while (++x < W_M) //W_M represents the width of the map
    {
        while (angle_s < FOV / 2) // cast rays
        {
            rayAdvance = 0;
            while (++rayAdvance <= (277 / cos(angle_s * M_PI / 180.0))) //comparing distance for every pixels in the ray to the ray distance
            {
                ray.x = w->posx + rayAdvance * cos(angle_s * M_PI / 180.0); // converting degrees to radians inside cosine and sine
                ray.y = w->posy + rayAdvance * sin(angle_s * M_PI / 180.0);
                if (ray.x < w->map->h && ray.y < w->map->h && w->map->board[(int)ray.y][(int)ray.x] != 0)
                {
                    printf("ray.x = %f, ray.y = %f\n, rayAdvance = %d\n", ray.x, ray.y, rayAdvance);
                    wall_hit = 1;
                    break;
                }
            }
            if (wall_hit == 1)
                draw_wall(w, rayAdvance, x);
            angle_s += 30.0 / W_M; // i devided the field of view so i can do the recursion for the other part of FOV
        }
    }
}


texts: Control Camera with gyroscope and place a gameobject always in front of it

texts:
Actually I have came here after searching from past 5-6 hours. Actually I am making a small game in which I have a camera and a gameobject. The Game Object is place in the center of the scene at 0,0,0 . My scene doesn't include anything but a skybox. I wanted to move my camera with gyro input, I got that working.
My problem is that I want my object which is at 0,0,0 is to face camera always. The camera is controlled by gyro so the object should always remain infront of the camera. I have taken a script from wiki.unity3d and it seems to be somewhat working. Actually I want an offset for the transform.lookAt or if it's not possible I'll require some solution for it.

public class CameraFacing : MonoBehaviour
{
    public Camera m_Camera;

    void Update()
    {
        transform.LookAt((transform.position) + m_Camera.transform.rotation * Vector3.forward,
                m_Camera.transform.rotation * Vector3.up);
    }
}

Actually I have tried 3rd person and FPS shooter camera and Camera Follow script as well besides knowing it doesn't fit my need. As In most cases we want the camera to follow object. But in this case my input is through gyro of mobile device and I want the center object to always remain in front of camera.

Here is the code for gyroscope. I have made the object which I want to always stay infront of camera as suggested by comment but the camera rotate with gyro but not the object that is child of it, which is pretty strange.

private float initialYAngle = 0f;
private float appliedGyroYAngle = 0f;
private float calibrationYAngle = 0f;
void Start()
{
    Input.gyro.enabled = true;
    Application.targetFrameRate = 60;
    initialYAngle = transform.eulerAngles.y;
}

void Update()
{
    ApplyGyroRotation();
    ApplyCalibration();
}

public void CalibrateYAngle()
{
    calibrationYAngle = appliedGyroYAngle - initialYAngle; // Offsets the y angle in case it wasn't 0 at edit time.
}

void ApplyGyroRotation()
{
    transform.rotation = Input.gyro.attitude;
    transform.Rotate(0f, 0f, 180f, Space.Self); // Swap "handedness" of quaternion from gyro.
    transform.Rotate(90f, 180f, 0f, Space.World); // Rotate to make sense as a camera pointing out the back of your device.
    appliedGyroYAngle = transform.eulerAngles.y; // Save the angle around y axis for use in calibration.
}

void ApplyCalibration()
{
    transform.Rotate(0f, -calibrationYAngle, 0f, Space.World); // Rotates y angle back however much it deviated when calibrationYAngle was saved.
}


texts:
I had a question about How to calculate the enemy to arrive in the middle of cell.

How to calculate the enemy to arrive in the middle of cell?

The posters pointed out that the direction of the enemy isn't needed because the velocity already has a direction. I modified the code -

if(position.x < start.position.x) {
            velocity.x = ENEMY_VELOCITY;
        }
        else if(position.x > start.position.x){
            velocity.x = -ENEMY_VELOCITY;
        }
        else {
            velocity.x = 0;
        }

        if(position.y < start.position.y) {
            velocity.y = ENEMY_VELOCITY;
        }
        else if(position.y > start.position.y){
            velocity.y = -ENEMY_VELOCITY;
        }
        else {
            velocity.y = 0;
        }
        position.add(velocity.x * deltaTime, velocity.y * deltaTime);

The enemy's movements were choppy after it go around the tower I added the range of the middle of a cell but it looks like it'll stop in certain places.

public void plotPath(Cell start, float deltaTime) {

        if(position.x < start.position.x && Math.abs((start.position.x - position.x)) > 0.01f) {
            velocity.x = ENEMY_VELOCITY;
        }
        else if(position.x > start.position.x && Math.abs((position.x - start.position.x)) > 0.01f){
            velocity.x = -ENEMY_VELOCITY;
        }
        else {
            velocity.x = 0;
        }

        if(position.y < start.position.y && Math.abs((start.position.x - position.x)) > 0.01f) {
            velocity.y = ENEMY_VELOCITY;
        }
        else if(position.y > start.position.y && Math.abs((position.y - start.position.y)) > 0.01f){
            velocity.y = -ENEMY_VELOCITY;
        }
        else {
            velocity.y = 0;
        }
        position.add(velocity.x * deltaTime, velocity.y * deltaTime);
    }

I think Math.abs((position.y - start.position.y)) is a wrong way to calculate. I tried to fix 0.1f to different value, but it'll stop somewhere after passing the tower or having choppy movements, it's much less than before.


texts: Difference between Arcade, P2 and Ninja physics in Phaser

texts:
I am a beginner and trying to learn game development using Phaser. Currently Phaser is providing three physics systems namely Arcade, P2 and Ninja. But I don't know the differences between them and I would also like to know in which scenario we should use a particular physics system?

Please give me some insight for these physics systems.


texts: OpenGL: Frame partially jumps back and forth

texts:
I'm working on a project with SDL and OpenGL. The game works great on Windows, Linux, OS X and iOS. However, the Android version is showing a problem on my phone in particular. I have tested another device and there it works great as well.

The problem I'm facing is a visual glitch. It happens in bursts: for example: 90 frames okay and then 40 frames the glitch. The glitch itself is kind of hard to describe but I'll try. The screen is being updated partially correct (from the top of my phone to approximately halfway down) and partially flickering. The flickering effect is some sort of back and forth jumping. I'm thinking that it is related to double buffering. I think that because what I get to see on the screen is jumping back and forth every frame. It is like half of the screen is one frame in time and the next frame 2 frames late. Pretty much like a procession of Echternach, I guess you could say. If I plot it in a chart where time goes on when moving down the chart, I think I'm seeing this (numbers in the table are the indices of the frames in my game loop I am actually seeing):

          left half | right half  (phone is in landscape)
         ------------------------
time  1 |      1           1
time  2 |      2           2
time  3 |      3           1
time  4 |      4           4
time  5 |      5           3
time  6 |      6           6
time  7 |      7           5
time  8 |      8           8
time  9 |      9           7

So the right half is one frame in time, and the next frame, it shows the previous frame. This is supports my theory that there is a problem with double buffering. It looks like it somehow doesn't get to completely update the backbuffer before it is put on the screen, or something.

Also, the split between good and glitch on the screen is different from frame to frame, which points I think proves it is a synchronisation issue and heavily depends on timing of what is going on. Adding glFinish(); before the SDL_GL_SwapWindow(); call doesn't help.

Version info:
SDL reports vsync to be turned on. However, I believe that this isn't tearing. My phone a Samsung Galaxy S3 mini and is running Android 5.1.1 (CM12) and the GPU (Mali-400) supports OpenGL ES 2.0. Other games run okay on my phone.


texts: How can I simple use global or individual bool flag/s?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoorsManager : MonoBehaviour
{
    public bool globalDoorsLockState = false;
    public bool[] doorsLockState;
    public GameObject[] doorsShieldFX;

    // Start is called before the first frame update
    void Start()
    {
        doorsShieldFX = GameObject.FindGameObjectsWithTag("ShieldFX");
        doorsLockState = new bool[doorsShieldFX.Length];

    }

    // Update is called once per frame
    void Update()
    {
        for (int i = 0; i < doorsLockState.Length; i++)
        {
            if (globalDoorsLockState == true)
            {
                doorsLockState[i] = true;
            }
            else
            {
                doorsLockState[i] = false;
            }
        }
    }
}

I want to be able to change all the doors flags to true/false or each door individually. Now in the Update it's working only for the global.

How can I add code or change it so it will also be able to change each door lock state individually?


texts:
A friend of mine and I are planning a game together to work on in our free time. It's not an extensive game, but it's not a simple one either.

He's working on the story behind the game while I'm working on the graphics and code.

I don't really know where to start with the game. We know what the basic type of game it's going to be and how it would be played, but I'm having a hard time of actually knowing where to begin.

I have Xcode open but I don't really even know what I should be designing first.

What is some advice for this writer's block? Where is a good place to start with a game?
Should I design all the graphics and layout before even touching Xcode? Should I program the things I know I'll have difficulty with first before getting to the easy stuff?


texts:
I've been trying to follow a tutorial of glew, but i can't run this glGenVertexArrays, it always leads to a memmory access violation!...

I tried glExperimental = GL_TRUE too, also updated my video card driver 2 times, but it doesn't run.

Btw, there's my code (to TRY to generate a simple triangle):

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

#include <glew.h>
#include <glfw.h>
#include <glm/glm.hpp>
using namespace glm;

#define GLFW_DLL
//#pragma comment(linker,  "/SUBSYSTEM:WINDOWS")
//#pragma comment(linker, "/ENTRY:mainCRTStartup")

int main()
{

    //glewExperimental = GL_TRUE;

    if(!glfwInit())
    {
        cout << "Failed to load graphics... " << endl;
        return -1;
    }

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    static const GLfloat g_vertex_buffer_data[] =
    {
        -1.0f, -1.0f,  0.0f,
         1.0f, -1.0f,  0.0f,
         0.0f,  1.0f,  0.0f,
    };

    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
    glfwOpenWindowHint(GLFW_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_VERSION_MINOR, 1);
    //glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, 0);

    if(!glfwOpenWindow(1024, 768, 0, 0, 0, 0, 32, 0, GLFW_WINDOW))
    {
        cout << "Failed to open window";
        glfwTerminate();
        return -2;
    }

    glfwSetWindowTitle("IfUSeeingThisMsgTheShitWorked");

    glfwEnable(GLFW_STICKY_KEYS);

    //Main loop
    do
    {
        cout << "happaned";
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, 0, (void*) 0);

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

        glfwSwapBuffers();

    }while(glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS && glfwGetWindowParam(GLFW_OPENED));

    return 0;
}

Also, I want to point out that this function doesn't work:

glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

so I had to change it to:

glfwOpenWindowHint(GLFW_OPENGL_PROFILE, 0);

Does it have anything to do with my error? hm.

I'm posting it here, just to make sure that there's no other thing I can do, other than buy a new video card.
I really want to use the modern OpenGL, it is pointless to learn the old one.


texts: How should I handle tiny objects in a physics engine?

texts:
I am making a 3D physics engine for throwing dice. Up until now a dice has been 1x1x1m and gravity has been 9.82 m/s^2. This of course does not look realistic as the dice will respond to everything in a way that looks a little bit slow.

To fix this I tried to just change all sizes to make a dice be about 0.02m along a side. This in turn made my inverse masses and inverse inertia matrices get very large values which lead to numerical instability.

What is the best route to handle this? Can I keep the scale up so that a dice is 1x1x1 and just change mass or size of acting forces? Or should I tweak something else?

I guess the same problem could turn up if you made a game with very large physical bodies like spaceships or something so I hope that someone has run into something similar before.


texts: Camera bounds grow along with the game scene editor in Unity

texts:
I am extremely confused by the Unity editor. Look:

I have an image,

And I want my camera to fit it perfectly. I have achieved so by using a size property of 540:

Notice how the viewport rect has 1 width and 1 height. If you run this game in a Samsung Galaxy S5, the sprite will fit perfectly in your device.

Now, resize the game scene view a bit (drag the Unity window border outwards to make it grow). Let's make it bigger. Then this happens:

The camera "white bounds" grew bigger! And the sprite no longer fits perfectly in the Galaxy S5!

My question is, then: why did the camera's bounds grow along with the editor window, if the viewport rect property never changed (it is still at 1 width an 1 height)?


texts: Client-side Prediction Divergence with Input Packets and Time Differences | Multiplayer FPS

texts:
I am running into a problem while implementing client-side prediction in my multiplayer FPS. I'm not entirely sure if I've completely and correctly understood the concepts. I have read the articles from Gambetta and from Valve, as well as several others.

What I'm currently doing is sending client input as key presses and key releases; the client sends when it presses 'W', for instance, and sends a packet once it has stopped pressing 'W'. The client then predicts the movement in a fully-deterministic way. The server then sends a position packets to all of the clients and the client checks if there is any divergence and corrects for it.

I am now running into the issue if the time between the input packets on departure differs from the time of the input packets on arrival, it will inevitably lead to small errors and massive divergence over time as the server will think the client will have pressed a key for longer or less time than it actually has. I haven't seen anyone mention this, so I'm questioning if what I'm doing is right.

Another issue I am seeing with this approach is that the client sends rotation updates to the server at 64hz (my tick-rate). This will, of course, lead to small differences in rotation from the server and client at specific times. Given that the movement is dependent on the orientation/rotation of the player, client-side prediction errors will inevitably ensue.

One way I was thinking that could fix the first problem, would be to send timestamps along with the input packets and have the server rewind positions and compensate for the delay imprecisions. Before I follow through with that, I am seeking some confirmation as to what I'm doing is right.

Any help would be appreciated! Thanks!


texts:
Is it possible to overlay one texture over another and make them into a new texture? It should also work with an offset.

Here's an example:

This texture

and this texture

should make this texture

It should be possible to change the position of one texture.


texts: How can I handle different keyboard layouts?

texts:
Let's say I have a game that uses WASD controls on a QWERTY layout. Trying to use these controls on, say, a Dvorak layout is not ideal (equivalent to <A:H on QWERTY). Obviously, I'd want to use the same physical keys as QWERTY would use (,aoe on DVORAK).

I've come up with a few possible solutions:

Force the user to use QWERTY

obviously not ideal, especially for international users

Change shortcuts based on keyboard layout (WASD -> ,aoe)

forces me to make layout maps for each supported layout (automatable)
easiest for the user if there are more shortcuts than just WASD

Force the user to define shortcuts themselves

More flexible
Annoying if there are lots of shortcuts
Can be used in conjunction with the second option

Use hardware keycodes

consistent across keyboards?

How is this type of thing usually handled?


texts: How to get multiple string values from override ToString()?

texts:
I want to get multiple string values(selectedNameand selectedCurrency) individually from public override string ToString()below.
How do I go on about it?

    using System.Collections;
       using System.Collections.Generic;
       using UnityEngine;

       [CreateAssetMenu(fileName = "Country", menuName = "Country/Country", order = 0)]
       public class country : ScriptableObject
       {
           [System.Serializable]
           public class Item
           {
               public string Name;
               public string Currency;
               public string Capital;
               public string[] City;

    public override string ToString()
    {
    string selectedName = this.name;
    string selectedCurrency = this.currency;
    return selectedName + selectedCurrency;
    }

           }

           public Item[] m_Items;
       public Item PickRandomly()
    {
        int index = Random.Range(0, m_Items.Length);
        return m_Items[index];
    }
}

I need to use the selected string values in the script below.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class GameController: MonoBehaviour
    {   public country country; //This is the scriptable object country
    public Text countryText;
    public Text currencyText;

    void Start(){
    countryText.text = country.PickRandomly().ToString(); // This is where I need the country name string to show up.
currencyText.text = country.PickRandomly().ToString(); // This is where I need the currency string to show up.
    }
    }

Right now it just displays a random country name and currency for example USA USD in both the fields.


texts: How to animate an arc from the middle in both directions

texts:
I have been able to make an arc that animates from one end to another using the following coroutine:

 IEnumerator AnimateArc(float duration)
{
    float waitDur = duration / pts;

    for (int i = 0; i <= pts; i++)
    {

        float x = center.x + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
        float y = center.y + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
        arcLineRend.positionCount = i + 1;

        arcLineRend.SetPosition(i, new Vector2(x, y));

        ang += (float)totalAngle / pts;

        yield return new WaitForSeconds(waitDur);

    }
}

How can I animate this arc from the middle in both directions

at a constant speed
with an ease (animates slightly faster in the middle and slows down towards the end)


texts: Correct GL settings to mix 2D and 3D rendering

texts:
I'm programming a 3D game engine with 2D GUI. The GUI objects have partially transparent textures and the transparency works more or less. The sky color is rendered in transparent areas of the textures but the 3D objects aren't.

This is my initialization code:

private static void initializeOpenGL() {

    //Enabling OpenGL functions
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);

    //Using them
    glCullFace(GL_BACK);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

}

And this is my code to switch from 2D to 3D and vice versa. I am confident it is being run at the correct time.

public static void switchTo2D() {

    if (currentRenderDimension != Dimension.DIM_2) {

        glMatrixMode(GL_MODELVIEW);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(0, Display.getWidth(), Display.getHeight(), 0);
        glViewport(0, 0, Display.getWidth(), Display.getHeight());
        glMatrixMode(GL_MODELVIEW);

        glPushMatrix();
        glLoadIdentity();

        currentRenderDimension = Dimension.DIM_2;

    }
}

public static void switchTo3D() {

    if (currentRenderDimension != Dimension.DIM_3) {

        glPopMatrix(); //From 2D
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(PreferenceHelper.getInteger("fieldOfView"), (float) Display.getWidth() / Display.getHeight(), 0.1f, 1000);
        glViewport(0, 0, Display.getWidth(), Display.getHeight());
        glMatrixMode(GL_MODELVIEW);

        currentRenderDimension = Dimension.DIM_3;
    }
}

I believe it should correctly switch the settings, but clearly it does not:

I have verified that the .png textures ARE transparent.


texts: How do some games save without creating data files?

texts:
I downloaded a game called Brain Exercise with Dr.Kawashima. It contains only one executable and no data files. However, it's still possible to save the game!

Where does the save data go?


texts:
First of all take a quick look at this :

https://www.youtube.com/watch?v=LQtKP-EymFM

So this is to give a idea of what I mean by following a path, basicly I am trying to understand how something like that would work out, I don't mean the sonic like motion, what I want is how do I constraint the movement to predefined path. But still being able to Jump.

The trouble I am having is how does it behave when falling from the loop? how does it know in the Spline/Path  it should align to?

What I want is a some sort or explanation on how something like that would be implemented, the motion is not my concern.


texts: How can I add orbit effect to the camera?

texts:
On my player I have the component Animator , Rigidbody , Capsule Collider , Third Person User Control script , Third Person Character script.

On the Main Camera there are two scripts but only one is activated for now : Camera Follow and Mouse Orbit With Zoom :

The Camera Follow script is working fine. The problem is when I'm activating the Mouse Orbit With Zoom script if I move the player with the keys WASD and also rotate orbit the camera with the mouse the player lose focus. He does change his direction according to the mouse rotation but also lost focus :

And also for some reason I can make the camera rotation to be diagonal:

The reason Main Camera is not child of the player is that it's making the camera stuttering and rotating very fast on place. That is why I added the Camera Follow script.
The Camera Follow script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform player;
    public Vector3 offset;

    // Update is called once per frame
    void Update()
    {
        transform.position = player.position + offset;
    }
}

The orbit script :
using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseCameraOrbit : MonoBehaviour
{
    public Transform target;
    public float speed;

    private void Update()
    {
        if (Input.GetMouseButton(0))
        {
            transform.RotateAround(target.position,
                                            transform.up,
                                            -Input.GetAxis("Mouse X") * speed);

            transform.RotateAround(target.transform.position,
                                            transform.right,
                                            -Input.GetAxis("Mouse Y") * speed);
        }
    }
}

My game is adventure game type and the main goal is to make player movement to be with the keys and also to be able to look around like orbiting with the mouse because only following the player will not show where to go , that is why I'm trying to add orbiting, but the orbiting part is just not working good.


texts: Let me explain -- I'm just looking for a way that I can link a number to a set of methods. I want to randomly generate a "difficulty" int, and pick out an event based on the number I get. IE, if I get an int of 3 I want that to point to a specific event. What's the best way to accomplish this? I was thinking of story the events in lists, but methods can't be in lists. I thought about making the methods into delegates and putting those in lists but that seems unnecessarily complicated. Also, in the future I think I'd want to put multiple events at each level which would sort of make putting them into array or lists difficult.


texts: Ergonomics studies on choosing keys on a keyboard?

texts:
I have the following problem:

My game supports multiple powers, that you can use when you want, or even mix them, I currently assigned them to the numbers on the top of the keyboard.

After so much time playtesting, I ended developing high skills in playing my own game, and several of my new tactics involve mixing powers, but I found that I keep pressing incorrect buttons, or that I need to pause, look at the keyboard, and unpause, or I plainly press the wrong button (like, I try to press 5, but press 6 instead).

I already expected this when I made the keybindings, but I don't found how to solve...

How I fix that?

EDIT: The game is a fast-paced action game, or arcade game... (you know, not necessarily on a genre, except it is action, and you aim for high-scores), so I cannot use random keys, I really need to allow the players to press the keys REALLY fast, ANY key that they need to press.


texts: How can I use keybord keys like W, A, S and D in GLUT and C++?

texts:
I want to use W, A, S and D keys like GLUT_KEY_LEFT.

My Code:

if (key == GLUT_KEY_RIGHT)
    rotate_y += 5;
else if (key == GLUT_KEY_LEFT)
    rotate_y -= 5;
else if (key == GLUT_KEY_UP)
    rotate_x += 5;
else if (key == GLUT_KEY_DOWN)
    rotate_x -= 5;

else if (key == GLUT_KEY_HOME)
    X1 += 0.5;
else if (key == GLUT_KEY_END)
    Y1 += 0.5;
else if (key == GLUT_KEY_INSERT)
    Z1 += 0.5;


texts: Unity Text Mesh Pro can not get referenced in VSCode

texts:
I am using Text Mesh Pro in my Unity 2019.3.4f. The TMP works fine in unity, but in the code editor, Visual Studio Code, the TMP related things are marked with red wave underline, which means the VSCode could not get the reference of TMP.
In my csproj file, the TMP reference exists, here are some related codes:
<ProjectReference Include="Unity.TextMeshPro.csproj">
  <Project>{e8ae9ed6-ed86-3de7-e777-7e6794b003b2}</Project>
<Name>Unity.TextMeshPro</Name>

ProjectReference Include="Unity.TextMeshPro.Editor.csproj">
  <Project>{af8771c0-66d3-f01a-48b5-78951bce8a23}</Project>
<Name>Unity.TextMeshPro.Editor</Name>

My TMP works fine in every aspects, but there are code warnings in the VScode, "could not fine the namespace of TMPro". Is there anyone know how to fix it?


texts: Simple square hit the wall and turn around without stopping

texts:
I am coding and making my very first plat former game in Unity 4.5 2D.

Basically I want my character to ping pong between two walls.

I have set up a GroundCheck and CeilingCheck. I was thinking to add a WallCheck on the left and right of the character to detect the walls, but I will have platforms in the air, and if the character doesn't make the jump and hits the platform on the side I don't want it to turn around, but simply slide off and continue in it's current direction until it hits the wall again.

Coding in C#
1. Get the character ping pong from wall to wall
2. Know the difference between hitting the wall and hitting the side of a platform.


texts:
I have a spiral made of balls. It's a spiral with equally distributed balls using the following formula (see link on math.stackexchange).

This is how it looks like:

Now, the spiral is rolling forward with some speed forwardSpeed.
I want to unfold the balls on the ground so they are placed one after another so I have to somehow synchronize the rotation speed of the spiral and the timing of the 'undocking' part of the individual balls.
To make it super clear, I just want the spiral to create a "trail" of balls behind itself.
I've tried various approaches including triggers on the ground so the balls stick to it or even
calculating the distance from "previous ball drop" and if the distance is higher than some threshold then I'd drop another ball.
But these approaches didn't work well and also seemed quite bad.
I want to do it with proper math so I will sleep well made sure that it will work with every possible spiral size.
To calculate the Y position of the spiral on the ground I do a little trick:
var spiralRadius = Mathf.Abs(firstBall.position.y - lastBall.position.y); // first and last balls connected to the spiral

and then I use it to set the Y position of the spiral in Update().
This works pretty well for removing balls from the tail - the Y position is adjusted accordingly so the spiral is always on the ground:
yPositionOffset.transform.position = new Vector3(0f, spiralRadius, 0f); // in Update

Ok now back to the problem
I have smth like this:
private float GetCircumference(float r)
{
    return 2f * 3.1415f * r;
}

void Update()
{
    float spiralHeight = GetSpiralHeight();

    this.rotationWrapper.transform.Rotate(new Vector3(3.1415f * Time.deltaTime, 0f, 0f));

    // SAND_BALL_DIAMETER is the scale of the ball
    float ballUndockInterval = SAND_BALL_DIAMETER / (spiralHeight * 3.1415f);

    if (Time.time > nextBallUndock)
    {
        nextBallUndock = Time.time + ballUndockInterval;
        UndockBallFromTail();
    }
}

void FixedUpdate()
{
    var forwardTranslation = forwardSpeed * Vector3.forward * Time.fixedDeltaTime;
    targetPos += forwardTranslation;
    var finalPos = Vector3.Lerp(rb.position, targetPos, Time.fixedDeltaTime * SpeedLerp);
    rb.MovePosition(finalPos);
}

And here's the result I get which looks like one of the trigonometric functions... what the hell?

Does anybody have any idea what is going on here?


texts: Streaming player voice (client -> server) without (minimal) noticeable voice breaking

texts:
I recently started to jump into voice streaming for my RPG game, for players to communicate by a central server point. I use TCP packets to communication from client->server and from server->client(s).

What I currently do is streaming the microphone from the client (push-to-talk), send the voice data in 4096 bytes chunks, and send them to the client. However, since TCP packets take some time to send and process, as well as standard latency issues, the server forwards the packets to other clients with a certain delay (sometimes up to half a second).

How should I compensate for this delay? (What technique do you recommend?)


texts:
I'm making a 2D retro-style pixel game and I'd like to know how big my sprites should be.
I'm not talking about the size of my image files (which I decided to use a 32x32-based artstyle), but the actual size of them once they are in Unity.
Should I keep a 1:1 scale and import all of my usually 32x32 sprites into Unity? Is there a special scale up or down process I need to do before or after import them?
I'm saying this because when I'm working with HUD elements, they are drastically really big compared to my tiny sprites, so I'm worried if this could affect implementing something like RigidBody or collisions,  and I should indeed scale up my sprites, or if this is normal and I'm being paranoic.
I'll append an image showing my concern.
BTW, the game looks so far as I wanted to, and it's working well, but right now it's more like a proto, so I'd like to resolve this doubt before continuing. Also, I test this usually in a 1920x1080 resolution, so maybe that's why the HUD looks so big.
Thanks!


texts:
I'm trying to import a map from Tiled to Unity. I have seen on several video tutorials (all of them on Windows) that they used Tiled2Unity in order to import such files. However, when I download Tiled2Unity, it does not accept .tmx files. It says that it wants .xml. Fair enough--I export it from Tiled as an .xml, and then it can't read the file.

Has anyone else had this problem? Anyone know how to deal with it?