texts: How to implement an arbitrary rules engine with interaction

texts:
Suppose that I have a game that has fairly simple rules, but may have any number of rules modifiers. For boardgames, the classical example would be Cosmic Encounter, but Slay the Spire or any number of games apply. The base rules are easy, but there are too many modifiers to explicitly write conditionals for them all. So how is this done?

(This could also be for any business logic rules engine, but games are where I seem to encounter this more often).

I would think you might be able to do this by having "state" objects and then passing them through a series of modifier objects, but I'm not sure this is the right way of doing it. What is the technique / style for this? What are some good primers/examples?

(I can program well enough, but with my EE degree have only whatever theory I've picked up on the job....).


texts: GetButtonDown for Unity keyboard UI navigation?

texts:
By default, Unity's keyboard navigation for buttons seems to check for GetButton rather than GetButtonDown--if a menu has 5 items and I hold the down arrow, it'll scroll very quickly to the bottom.

This feels awkward; it would make more sense to check for GetButtonDown and only move 1 space per input. However, I can't find any option to let me change that. Any ideas or workarounds?


texts: Setting uniform value of a vertex shader for different sprites in a SpriteBatch

texts:
I'm using libGDX and currently have a simple shader that does a passthrough, except for randomly shifting the vertex positions. This shift is a vec2 uniform that I set within my code's render() loop. It's declared in my vertex shader as uniform vec2 u_random.

I have two different kind of Sprites -- let's called them SpriteA and SpriteB. Both are drawn within the same SpriteBatch's begin()/end() calls. Prior to drawing each sprite in my scene, I check the type of the sprite.

If sprite instance of SpriteA: I set the uniform u_random value to Vector2.Zero, meaning that I don't want any vertex changes for it.
If sprite instance of SpriteB, I set the uniform u_random to Vector2(MathUtils.random(), MathUtils.random().

The expected behavior was that all the SpriteA objects in my scene won't experience any jittering, while all SpriteB objects would be jittering about their positions.

However, what I'm experiencing is that both SpriteA and SpriteB are jittering, leading me to believe that the u_random uniform is not actually being set per Sprite, and being applied to all sprites. What is the reason for this? And how can I fix this such that the vertex shader correctly accepts the uniform value set to affect each sprite individually?

passthrough.vsh

attribute vec4 a_color;
attribute vec3 a_position;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;
uniform vec2 u_random;

varying vec4 v_color;
varying vec2 v_texCoord;

void main() {

    v_color = a_color;
    v_texCoord = a_texCoord0;

    vec3 temp_position = vec3( a_position.x + u_random.x, a_position.y + u_random.y, a_position.z);

    gl_Position = u_projTrans * vec4(temp_position, 1.0);

}

Java Code

this.batch.begin();
this.batch.setShader(shader);

for (Sprite sprite : sprites)
{
    Vector2 v = Vector2.Zero;
    if (sprite instanceof SpriteB)
    {
        v.x = MathUtils.random(-1, 1);
        v.y = MathUtils.random(-1, 1);
    }

    shader.setUniformf("u_random", v);

    sprite.draw(this.batch);
}

this.batch.end();


texts: Calculating orbital elements from Cartesian Vectors

texts:
I'm having serious troubles with getting my calculations to work. I'm calculating the orbital elements from a position vector, and a velocity vector. (I also know the distance and mass of the bodies around)

The equation for angular momentum is as follows: h=r*v

The equation for eccentricity is: e=((v^2−μ/|r|)r-(r⋅|v|)v/µ

I plug in the position and velocity to get h, and I plug them into the other equation to get the eccentricity. These SHOULD be constants, and not change unless another force is put on them... yet they are not constant. In fact they change as the orbit goes around.

In the diagram I have just left a trail to show the orbital path. I should be able to calculate the required information... however they rely on the constants, which are not at all constant. I reference the rigidbody's position and velocity in them, and I've entered the equations in correctly. My code for applying force between planets is as follows:

void CalculateForce(Transform body) {
    float m1 = rbody.mass;
    float m2 = body.GetComponent<Rigidbody> ().mass;
    float distance = Vector3.Distance (transform.position, body.position);
    float f = (m1 * m2) / Mathf.Pow (distance, 2);
    Vector3 direction = rbody.position - body.GetComponent<Rigidbody> ().position;
    rbody.AddForce (-direction.normalized * f);
    body.GetComponent<Rigidbody> ().AddForce (direction.normalized * f);
}

The calculations are coming back incorrect. The eccentricity varies between 0.9 and 1.1. Anything over a 1 is not actually in orbit, and anything less is in orbit. However this remains in orbit as it travels around.

Can anybody help? (I've already posted to the space stack exchange and had no luck)

Thanks in advance.

Update:

Code used to calculate eccentricity (1001f is the combined weight of both objects):

    Vector3 pos = GetComponent <Rigidbody2D> ().position;
    Vector3 vel = GetComponent <Rigidbody2D> ().velocity;
    Vector3 eccentricity = (Mathf.Pow (vel.magnitude, 2.0f) - (1001f / pos.magnitude)) * pos;
    eccentricity -= Vector3.Dot (pos, vel) * vel;
    eccentricity /= 1001f;


texts: What do sandbox games usually do when generating new terrains?

texts:
I am trying to make a minecraft. In my game, when the player moves to the boundary, new chunks will be generated.

What I do is creating new chunks in my main thread and generating a new VBO to store them. But I find that it's quite inefficient and you can obviously feel the FPS is decreasing.

What do these kinds of games usually do when generating new terrains? Do they use multi-threads or some specific efficient algorithms or compute shaders (I still don't know much about OpenGL)? I once tried to generate my new terrains in another thread. But I found I can't use GL operation to generate VBO in another thread. I am thinking about pre-generated some VBOs in my main thread. Is that the right way?

I want to know what most people do in this situation.


texts:
Here's an example (this if() is inside of a for loop, which itself has the [unroll] attribute):

[dynamic]
if (n.x > 1.0f || n.x < -1.0f || n.y > 1.0f || n.y < -1.0f || n.z < 0.0f || n.z > 1.0f)
{
    break;
}

I've never seen this before, but I stumbled across this in a shader I'm trying to convert to glsl. Searches turned up nothing but the SM 5 dynamic linking ability. I looked at the available if() attributes, and there's only [branch] and [flatten] listed.


texts: XNA Skinned Model - Keyframe.Bone out of range exception

texts:
I'm getting an IndexOutOfRangeException on this line of AnimationPlayer.cs:
boneTransforms[keyframe.Bone] = keyframe.Transform;

I don't get what it's really referring to. The error happens when keyframe.Bone is 14, but I have no idea what that's supposed to mean. The 14th bone of my model? What would that even be? I read this thread, but nothing there seemed to work. I don't have many bones, stray edges/verts, unassigned verts, unparented/non-root bones, or bones with dots in the name. What else can I be missing?

Thank you for any help!


texts: How do I convert my matrix from OpenGL to Marmalade?

texts:
I am using a third party rendering API, Marmalade, on top of OpenGL code and I cannot get my matrices correct. One of the API's authors states this:

  We're right handed by default, and we treat y as up by convention. Since IwGx's coordinate system has (0,0) as the top left, you typically need a 180 degree rotation around Z in your view matrix. I think the viewer does this by default.

In my OpenGL app I have access to the view and projection matrices separately. How can I convert them to fit the criteria used by my third party rendering API?

I don't understand what they mean to rotate 180 degrees around Z, is that in the view matrix itself or something in the camera before making the view matrix. Any code would be helpful, thanks.


texts: How to find and send data about on-screen players to a client in a real-time multiplayer game?

texts:
I'm surprised I couldn't find much information on this.

I am making a top-down browser game in which the players see a small section around their player (see the image). Since the player doesn't need to render the players far away that they can't see, it would be unnecessary to send data about them. I want to know how the server should calculate who is near enough to the client that they appear on their screen and therefore receive data from the server about those players.

The way my problem differs from what I have found is that I need to track many players (at least 50 and preferably up to 100) and many can be on screen at one time (assume a maximum of 10 on screen at any one time).

Some assumptions/considerations that are made:

The players are always moving and positions constantly changing
Must handle at least 50 players at one time (preferably up to 100)
Players can drop in and out at random locations so should be able to adapt to this quickly
Screen sizes vary
Player input is just movement (but there should be scope for other simple actions)
Data sent over TCP as will be browser based
Node.js server

Initially I thought about sending data for all the positions of the players to each player but this seems like a terrible idea with so much unnecessary data being sent - from what I understand the server should be sending as little as possible.

My current strategy (shown in the image) is to have the server periodically (every second for example) calculate the distances between all players to determine those near enough to each other to appear on screen. For the next second, data will only be sent to the client regarding those near it. After the next second, new distances are calculated to decide what to send (and render) for each player.

Some problems to take into account:

A lot of calculations must be performed by the server for all the players
Extra information would need to be sent about players just outside the screen to account for any movement between updates
Interpolation would probably be required
Different screen sizes will mean that some players can see more than others (the fairness isn't the issue here, but tracking to what distance to let players see)

The main issue is the ability of the server to process all of this with everything else that it must already do.
I am not convinced this is a very good way.

This is trivial for off screen entities in a single player game, however for multiplayer games with many players moving at once this becomes much more difficult.

How can I figure out what players are on screen efficiently and what data should be sent regarding this?
Or please point me to where I can find information on this.


texts: I have a top down view of the interior of a house. I want to put a cover on the top so light from outside can't come in and I get more realistic lighting inside but transparent so I can still see inside. No clue how to achieve this in Unity. Any help would be appreciated. Ideally I'd just be able to use Unity's built in cube to make this.


texts: Optimal OpenGL 2D Sprite Batching (Best Practice)

texts:
I am working on simple 2D engine using OpenGL (3.3+) for rendering and was wondering what the optimal method of sprite batching would be. I plan to put all sprites into one (or fewer) texture atlases. Unsurprisingly, each sprite consists of 2 triangles and 4 texture coordinates.
For simplicity, let's assume only the sprites are not animated for now.

Now to my question, I do not know what would be the optimal way to draw them. As far as I was able to dig up, I have two options:

Draw each sprite separately, which would allow me to modify the position/rotation/scale of each sprite within the shader via MVP matrices. This also means that I would not need to update the sprite data buffers (vertex pos. & tex. coords) on GPU.
Stuff all sprites' data into a single VBO and draw them all with one glDrawElements call (assuming they use the same texture atlas and shader). However, I would then need to update the VBO every frame (or at least the changed parts, which also means that I would have to watch every sprite's state).

Which of these options is better from a practical point of view? Or is there any other method to achieve what I'm trying to do?


texts: How to prevent corner slipping with a shortest axis collision solver

texts:
Currently I use AABB's to represent objects in my game engine, I resolve collisions between them by finding the shallowest axis, but this leads to a problem if an object is approaching another in a way that their corners would collide at a fast velocity, they will slip past each other and resolve on the wrong axis because one penetrated too deeply, for example:

We can see that the red square is approaching the green rectangle. They intersect and the solver sees that the smallest intersection is on the Y axis

Thus they sepparate on the Y axis, and the red square flies by the green rectangle, when it should have stopped on the left edge

I'm currently at a loss on how to solve this, any sugestions or fixes would be greatly appreciated!


texts: Using XML in XNA to display maths questions which are associated with objects

texts:
I've got a snake game with three objects: apple, pear & orange. I would like these to be associated with questions which I'm trying to create in XML. This is what I've done so far...

<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
<Asset Type="System.Collections.Generic.List[System.String]">

<MathsQuiz>

<Question Value ="What is 3 x 3? Orange = 9, Pear = 10, Apple = 12" Right ="orange">
    <answer Value ="orange"/>
    <answer Value ="pear"/>
    <answer Value ="apple"/>
  </Question>

</MathsQuiz>
</Asset>
</XnaContent>

I'm getting the error:
"Error There was an error while deserializing intermediate XML. 'Element' is an invalid XmlNodeType. Line 7, position 6."

I'm guessing it's because of the line MathsQuiz but not sure.

Any help is much appreciated!

Thanks, Tom


texts: Do game engines compile games or just interpret them

texts:
I know that many game engines like Unity3d use scripting languages like c# or java script but does that mean that a game engine is just an interpreter?

If so, does that mean that if I move the executable of a game made with Unity to the folder of another game made with the same engine then the game will run fine because all the engine is doing is interpreting the code?

If not does the engine just ship with a compiler and turns scripting code into compiled code?


texts: How can I draw a sprite that inverts the colors behind it for an aiming reticle?

texts:
In XNA, how can I draw a sprite on the screen that inverts the colors behind that sprite (i.e. the colors that would appear if the sprite weren't in the way of them)?

I feel this is the best technique for an aiming cursor in a game, but I'm unsure how I can achieve this. I'm open to other ideas for aiming cursors if this is less than ideal.


texts: What are the ways to deal with elevated tile blocking the view of the tile behind it?

texts:
I'm trying to make an isometric tactical rpg type of game. One issue I encountered is that if I elevate an tile, then it starts to block the view behind it. The game is 2D, so there is no freely rotating cameras.

Example:

Flat ground with a person on the top tile

Elevated ground blocking the person

Some of the options that I've thought about include:

When the character is blocked by a tile, display the outline of the character. But I don't like this option because it kind of breaks immersion, and makes it difficult to do "surprise" kind of factor where an enemy character jumps out from behind a blocked tile.
Have the option to rotate the camera by 90 degrees, 180 degrees, and 270 degrees, so you can have see all around it. However, this still doesn't solve the issue where if you have a 4 really tall tiles blocking a single tile in between since no matter how you rotate it, it's still being blocked.
Bigger character and smaller elevation so that even when there's elevation, you can still see part of the character behind it. This only mitigates small elevation differences like hills, but not when you are trying to make a cliff type of terrain.
Have only higher tiles near top of the map, and lower tiles near the bottom. This avoids blocked tile completely, but sets constraints on map making.
Have the option to toggle flattening the map. Such that when turned off, you can see the elevation but blocks the tile behind, and when it is turned on, you don't see elevation, but you can see all tiles.
Combination of the above

So the question is, is there any other ways to solve this issue?


texts: Check whether a vector is to the left or right of another position

texts:
I don't know how to decide if my point is on the left or right side of another object.

My first thought was to check if x-axis of object1 is bigger or smaller than object2's, but if my objects rotate then that isn't working.

In the picture above we have two states where object2 is on the left side of object1. In one case its x coordinate is greater, in the other, its x coordinate is less.


texts: Make CharacterControllers in Unity not collide with each other

texts: I'm trying to spawn a number of CharacterControllers and have them move around an area, but they keep getting stuck on each other. Is there a way to make them pass through each other while still respecting the terrain's obstructions?


texts: C# Integer limits for Scriptable Objects

texts:
I am experimenting with Scriptable Objects in Unity. In the following example how can I limit the range of accepted values?

public class AScriptableObject : ScriptableObject
{
   public uint damage;
}

Since it's a uint the lowest value is 0 but how can I limit the max value to 500 for example? Can I use if statements?


texts: How can I ensure my Collada model fits on an iPhone screen?

texts:
Hi I am new to game development. I see many examples and tried myself like displaying triangle, cube etc. Now I am looking to render a Collada object. So I created a Collada object using Google Sketch up and trying to render that now. But the thing  I am not understanding is, in all examples the vertices are between -1.0 and +1.0 values. But when I looked into that Collada file, the vertices were ranging from -30.0 to 90.0. I know any vertices greater than 1.0 will not display on iPhone. So can you pleas tell my the secret behind converting Object coordinate to normalized vector coordinate?

My previous triangle defined as

struct Vertex{

    float Position[3];
    float Color[4];
};
const Vertex Vertices[] = {
    {{-0.5, -0.866}, {1, 1, 0.5f, 1}},
    {{0.5, -0.866}, {1, 1, 0.5, 1}},
    {{0, 1}, {1, 1, 0.5, 1}},
    {{-0.5, -0.866}, {0.5f, 0.5f, 0.5f}},
    {{0.5, -0.866}, {0.5f, 0.5f, 0.5f}},
    {{0, -0.4f}, {0.5f, 0.5f, 0.5f}},
};

And now triangle from collada is

const Vertex Vertices[] = {
    {{39.4202092, 90.1263924, 0.0000000}, {1, 1, 0.5f, 1}},
    {{-20.2205588, 90.1263924, 0.0000000}, {1, 1, 0.5, 1}},
    {{-20.2205588, 176.3763924, 0.0000000}, {1, 1, 0.5, 1}},
    {{-20.2205588, 176.3763924, 0.0000000}, {1, 1, 0.5, 1}},
    {{-20.2205588, 90.1263924, 0.0000000}, {1, 1, 0.5, 1}},
    {{39.4202092, 90.1263924, 0.0000000}, {1, 1, 0.5, 1}},
};


texts: Diagonal movement behaving strangely when other key is pressed

texts:
I'm following the tutorial at http://blog.sklambert.com/html5-canvas-game-the-player-ship/. I'm at the part where bullets get added to the game. Prior to this in the section about movement where I split the movement loop into two seperate loops, one for up-down and the other for right-left movement. When one of each is pressed the ship moves diagonaly.

How it was presented in the tutorial.

if (KEY_STATUS.left) {
            this.x -= this.speed
            if (this.x <= 0) // Keep player within the screen
                this.x = 0;
        } else if (KEY_STATUS.right) {
            this.x += this.speed
            if (this.x >= this.canvasWidth - this.width)
                this.x = this.canvasWidth - this.width;
        } else if (KEY_STATUS.up) {
            this.y -= this.speed
            if (this.y <= this.canvasHeight/4*3)
                this.y = this.canvasHeight/4*3;
        } else if (KEY_STATUS.down) {
            this.y += this.speed
            if (this.y >= this.canvasHeight - this.height)
                this.y = this.canvasHeight - this.height;
        }
        // Finish by redrawing the ship
        this.draw();

What I did.

 if (KEY_STATUS.left && this.x >= 0) {
            this.x -= this.speed
        }
        else if (KEY_STATUS.right && this.x <= this.canvasWidth - this.width) {
            this.x += this.speed
        }
        if (KEY_STATUS.down && this.y <= this.canvasHeight - this.height) {
            this.y += this.speed
        }
        else if (KEY_STATUS.up && this.y >= 0) {
            this.y -= this.speed
        }

        // Finish by redrawing the ship
        this.draw();

All was fine at first, the ship was moving as I wanted it to. Then I added.

if (KEY_STATUS.space && counter >= fireRate) {
        this.fire();
        counter = 0;
    }

Now the movements work fine untill I press the Space key. This is what confused me the most. While Space is pressed, only the UP+Right, diagonal movement works, while all the other default to one or the other.
 Ex: UP+Left gives Up or Left depending on which was pressed first.
 As far as I can tell the problem has nothing to do with the order of the comands in the loops. Some sources suggest that it might be a problem with my keyboard.BTW, I've ran across this problem with a similar project(c++,sfml). So am I messing up something in my code or should I get a new keyboard?
PS: I copied almost all of the code from the tutorial.Still has the same problem.


texts: XNA mesh.Draw() takes the longest CPU time

texts:
We have a problem. Our game steadily slows down as we increase the number of models we draw. When the number reaches 100 - FPS is dead. Our humble tests showed that the reason is not GPU. This is what we did:

Rendered models with the most basic shader code - nothing changed;
Checked the NVidia NSigt metrics - GPU was less and less loaded per second as we increased number of models;

At the same time, a simple Windows Task manager showed that, as the number of models rise, the load increases (up to a 100%) on the single CPU core that our game uses. So we are pretty sure our game is running slowly because of the CPU.

We then moved on and tried to identify which line exactly causes the problem. We used c# TimeSpan metrics and timers for that. Our research showed that the biggest cause of the slow performance is... mesh.Draw() function used by every model that we draw.

We tried commenting this very line and things improved instantly (ofc. nothing was drawn on the screen).

So the question is, what are we to conclude from this? mesh.Draw is a closed function and we cannot optimize it. Trying to bruteforce parallel it is impossible (i guess it was natural). But something tells me that we need to look elswhere if this function is slowing the CPU, the question is where?

Update: here is the code I use to draw the model:
            public void Draw(...)
            {
                int index = 0;

            int i = 0;

            foreach (ModelMesh mesh in Actor.Model.Meshes)
            {

                bool isDrawable = false;
                #region Check if this ModelMesh needs to be drawn according to PartsToDraw (string) list.
                foreach (string s in PartsToDraw)
                    if (s == mesh.Name)
                        isDrawable = true;
                #endregion

                if (isDrawable)
                {
                    int effectStartIndex = index;
                    foreach (Effect effect in mesh.Effects)
                    {
                        if (Actor.MatrixPaletteParams[index] != null)
                        {
                            Actor.WorldParams[index].SetValue(World);
                            Actor.MatrixPaletteParams[index].SetValue(Actor.Palette[i]);
                        }
                        else
                            Actor.WorldParams[index].SetValue(Actor.Pose[mesh.ParentBone.Index] * World);

                        if (drawType != null && drawType.DrawShadow)
                            SetShadowEffectParameters(effect, renderer, drawType.DrawShadowMort);
                        else
                        {
                            SetCommonEffectParameters(effect, renderer);
                            SetLitEffectParameters(effect, renderer, drawType);
                        }

                        index++;
                    }
                }
                else
                    index++;

                if (isDrawable)
                    mesh.Draw();

                i++;
            }
        }

"Set...EfectParameters" methods mostly consist of effect.Parameters["SomeParameter"].SetValue() calls. I pass around 30 parameters to the GPU there, mostly floats, matrices and bools. Moreover each ModelMesh has three textures that it passes into the GPU. I have no idea how fast this works and if it can be optimized. It should be fast.

You should also note that I draw a skeletaly animated model using Dastle's XNA Animation Component library. Once again, I understand that this might be the reason behind lags, and we did find the weak spot of the animation code, but why on Earth does the metrics show that mesh.Draw is the slowest spot? What is happening there?


texts:
I've had this little problem for a while now, where for some reason my calculations for per-vertex normals results in a weird distortion or warping, skewing my lighting, shading, and reflection passes.

In spherical geometry, it noticeably distorts at the beginning and end, resulting in an imperfect transition in a cubemap reflection:

In rectangular geometry, normals are quite warped and skewed on an angle:

Same perspective (top down), but switched over to the normal map:

My approach for calculating per-vertex normals is to cycle through all the vertices in a mesh, while also looping through each triangle in the mesh (inner loop). I check if the desired vertex exists in the triangle, and if so I sum that triangle's normal into the normal for that vertex. After all the normal's have been summed together for a given vertex, I normalize it.

My implementation of the above is as follows:

QVector<GLushort> *i = getIndices();
QVector<QVector3D> *n = getNormals();
int total = i->size();
n->resize(total);

if ( total > 0 )
{
    // Loop through each vertex in mesh
    for (int x = 0; x < total; x++)
    {
        QVector3D normal = QVector3D(0,0,0);

        // Loop through each triangle in mesh
        for (int y = 0; y < total; y+=3)
            if (doesTriangleContainVertex( i->at(y), i->at(y+1), i->at(y+2), i->at(x)) )
                normal += calculateTriangleNormal( i->at(y), i->at(y+1), i->at(y+2) );

        n->replace(x,normal.normalized());
    }
}

My calculation for a normal for a given triangle is just the cross product of (vertex2-vertex1 and vertex3-vertex1).

Does anyone have any ideas as to why this is happening? The underlying shading methods work fine,  at least with per face normals,  but that obviously gives a faceted look, which I'm trying to avoid.


texts:
I've developed a game using MonoGame for Android (with Xamarin). When deploying to my Android device (via the Xamarin Studio IDE) it installs 3 apps - Monogame-Android-8-support, Monogame-Shared-Runtime and the actual game.

Now I'd like to know how you can package all those into one APK in order to publish the app.


texts:
I'm working on a 2D tile based game. I want NPC's to be able to destroy tiles, and ideally I would have a function, which takes a central x,y and then based upon a circular area from that point (radius) gives me all the tiles that fall within that circular area so I can destroy them.

Any ideas as to how to do this?


texts: Collision from the underside of a cylinder (Unity C#)

texts:
A quick introduction to my problem at the moment: I am currently having trouble with checking whether or not a cylinder is grounded. I am using a mesh collider (octagonal prism) as my main collider for the object, however I can't seem to get a reliable ground detection beneath it. I have tried using a trigger and raycasting, but neither seem to work correctly.

It would be a great help if you could either provide a method of correctly raycasting the cylinders base, or an alternate method (bearing in mind the object rotates on all axis). Many thanks in advance. (terrible diagram below)


texts:
I would like to explore realtime software based rasterization. I know everything is going towards the GPU these days but there are a few games where it still makes sense to use a software renderer.

For example: Voxeltron

  Voxatron is an arena shooter that takes place in a world made of
  voxels (little cubes, kind of). Everything in the game is displayed in
  a virtual 128x128x64 voxel display, including the menus and player
  inventory. If you look closely, you can sometimes see the inventory
  (score/life/ammo) casting a shadow on some of the objects on the
  ground.

  I've been working on voxel rendering and modeling tools for a long
  time now, with the ultimate goal of making a large explorey adventure
  game. About half a year ago it fused with work I was doing on arena
  shooters for Conflux, and this is the result.

  It's quite a simple game at heart -- mostly just Robotron set in a 3d
  destructible world with goofy creatures. I'm unsure how major the
  implications of destructibility will be for gameplay, but it sure is
  fun to blast away pieces of wall. I've also added an experimental
  wall-building pickup you can use to construct barriers to hide from
  scary monsters.

  The game takes place in a small set of arenas. Some of them feature
  rooms with set action pieces, somewhere between Knightlore and Smash
  TV. This is some of the original adventure based design sneaking back
  in, and an excuse to create thematic environments.

  Features:

  Custom software rendering with soft shadows.
  Built-in sound and music    synthesizer (also used to make the
  trailer music).
  Playback & post game recording.


texts:
We are using Unity 5.5 and Parse 1.7.0 (and Firebase for notifications) which doesn't have "Parse.Unity.dll" and while on Editor everything is working fine but when we build using "IL2CPP" on iOS; while running on device the game produces an error of "MissingMethodException: No constructor found for Parse.Common.Internal.FlexibleListWrapper`2".

I think it's because of stripping, I've tried to include "Parse.Core" and "Parse.Common" in "link.xml" but still same error while I was looking for solutions I found that there's a file "Parse.Unity.dll" that should have been in the project from the start but when I try to include it in our project another error but this time in Unity Editor that says "System.Threading.Tasks.Task is defined multiple times" and that's because -I think- the new Parse.Unity.dll and Unity.Task.dll from Firebase, if I try to delete that firebase Dll another error appears....

Please any help is appreciated :(

We have to build with il2cpp to upload on the App store, Android version works fine.


texts: What causes "ETC1 cannot be resolved" errors when building AndEngine?

texts:
I just got the latest AndEngine code from Mercurial, added Android 1.6 to my Order/Export tab, and cleaned everything (including a "Fix" command as instructed by the console). Regardless of which version of Android I specify in my project settings (1.5, 1.6, 2.2, 3.2), I get around 523 compilation errors.

The most unique I can see is ETC1 cannot be resolved, accounting for 5 out of 105 errors I can see.

The other 100 are all some variation of The method [...] must override a superclass method.

What am I missing? I installed the JDK, Eclipse classic, SDK manager, and everything in the SDK.


texts: How do I change my gravity and jumping logic to put the character at a specific height at a specific point in time?

texts:
I'm making a 2D platformer on Android using libGDX. One thing I've had a problem with recently is gravity and jumping. I found a few tutorials on the internet and was able to come up with this...

public static final int JUMP_HEIGHT = 64;
public static final float JUMP_GRAVITY= -6.0f;
public static final float MAX_GRAVITY = 20.0f;
public static final float GRAVITY= 19.0f;

private void updateGravity(float delta) {
    if(Gdx.input.isTouched() && !jumping) {
        jumping = true;
        gravity = Config.JUMP_GRAVITY;
    }

    if(jumping) {
        // change frame to jump
        sprite.setRegion(walkFrames[0]);
        sprite.translate(0, (-1*gravity));
        // runner has landed?
        if(sprite.getY() <= idleY) {
            jumping = false;
            sprite.setPosition(Config.RUNNER_X, idleY);
        }
        // slowdown / fall
        if (gravity < Config.MAX_GRAVITY) gravity += Config.GRAVITY*delta;

    }
}

The code works and my character will jump and fall smoothly. Although the time it takes for him to jump and comedown is independent from delta the height he jumps is not. If the device lags while jumping he will jump only a portion of how high he should. For the life of me I cannot get it to make sure it jumps a specific height (JUMP_HEIGHT) and in a specific time independent of the delta.


texts: Do inventory items have to live in the game world?

texts:
I'm trying to create an inventory system. There's a few parts to it:

Item (scriptable Object just the data like name etc of the item)
ItemDatabase which takes array of Item (scriptable object) and then on awake it looks through and populates a dictionary for ID,data
ItemStack - Actual item holds an int for an ID so it can get data from the dictionary from it.

My inventory has a list of ItemStacks, but to be able to populate that array the script needs to be on a GameObject, so with how everything works, is it required for me to always have GameObjects in the game basically representing items? I'm new to inventories so is that how its suppose to be? Or am I missing something here? It seems kinda strange if I have 700 different item in my inventory that would require 700 GameObjects created to represent them.

Or maybe I'm overthinking it... but I feel like the inventory should only have "data" and not a GameObject, the GameObject would be for when you spawn an item in the world.


texts: How to export an IK structure created in Blender 2.8 to Godot 3.1?

texts:
I created this IK bone structure in Blender 2.8 and exported as .escn

As you can see, in Blender it's working ok.
Now, how to use it in Godot?

I've tried export with:

.dae (native)
.dae (Better Collada)
.escn
.glb

None of them worked...

Is there any tutorial for using imported IK in Godot?


texts: Animation is slow on iOS Device and fast in Unity editor?

texts:
I had made a Settings popup in the game and animated it like scale animation (from 0 to 1) values.
It is appearing very smooth and works good in the unity Editor, but after building to the device it appears laggy and jerky.

I have also changed targetFrameRate to 60 but it does not works.
My Game is running at 60 fps but why my animation is running slow and jerky on Device?

Can anyone tell me what i am doing wrong..

Here is my Code:

public void ShowSettings()
{

    settingsAnim.SetBool ("isHidden",false);

}
public void CloseSettings()
{

    settingsAnim.SetBool ("isHidden",true);
}


texts: How can you pass a large amount of textures or equivalent to the fragment shader in OpenGL?

texts:
I am adding shadow mapping to a game engine I am working on.

For this effect, each light source needs it's own associated shadow map cube texture.

I am going to be exaggerated and say there can be up to 1000 lights in the world at a given time (this would most likely lag the entire thing, but that's not the issue).

This means I need up to 1000 depth maps loaded into the shaders at any one time.

According to:

GLint temp;
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &temp);
cout << temp << endl;

I have up to 4 texture units available. And the way I am currently passing my shadow maps is:

void Shadow_Map::load_to_GPU(GLuint program, GLuint index)
{
    glUseProgram(program);
    glActiveTexture(GL_TEXTURE0+index+1);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

    string name = "depth_maps[" + to_string(index) + "]";

    GLint loc = glGetUniformLocation(program, name.c_str());
    if(loc == GL_INVALID_VALUE || loc==GL_INVALID_OPERATION)
    {
        cerr << "Error returned when trying to find depth_map uniform."
             << endl;
        return;
    }

    glUniform1i(loc,1+index);
}

So under my current methods I am very far away from the amount of depth map cube textures I need to use. Is there a better way to pass a large amount of cubicTextures, or what other techinique could I use to be able to handle large amounts of point lights?


texts:
I'm making a Pong game to get started with game-developement but
I've run into a problem that i can't figure out.

When trying to change the balls direction it doesn't change. This is the relevant code:

function moveBall(){
    this.speed = 2.5;
    this.direction = 2;
    if(this.direction == 1){
        ball.X +=this.speed;
    }
    else if(this.direction == 2){
        ball.X -=this.speed;
    }
}

function collision(){
    if(ball.X == 500){
        moveBall.direction = 2;
    }
    if(ball.X == 300){
        moveBall.direction = 1;
    }
}

Why doesn't it work? I've tried many different ways, and none of them seem to work.
The moveBall.direction changes though, since it alerts the new direction once it reaches the defined ball.X position.

If someone could help me I would deeply appreciate it.
I've included a JSFiddle link.

http://jsfiddle.net/hustlerinc/y4wp3/


texts: How do you do AI path following within a 2d physics engine like farseer/box2d?

texts:
I'm in the process of moving a 2d top down game I've been working on into a proper rigid body physics engine like Farseer. Up until now, I had just hacked together my own physics code where needed.

I'm trying to learn the proper way of doing things here.

What is the proper way to make your AI follow a set path once you have made them rigid bodies inside of the physics engine?

If I have a path of navigation nodes on my map that I need the AI to follow, previously I would just move them along the path manually by calculating the next position they should be at for the next time step and manually setting them to that position.

But now they are rigid bodies and subject to collisions and any forces that may hit them and knock them off path.

So to make the AI move I believe I should now be applying impulses/forces to them? I should no longer be manually setting their position each frame.

So I think I need to go from a deterministic world where I force the AI to strictly follow a path to a non-deterministic world where they could get knocked about in any direction if hit and I simply nudge them towards the next node in the path to make them move.

Is that right? Is that how other people do it?

This raises some questions about how to then avoid your AI getting stuck on corners of scenery now that they aren't walking a precise path, how do you guys handle that type of thing?

Or is it better to somehow mix the two and still have your AI follow a fixed path by setting their position manually, and only react to other forces under certain circumstances you can easily control?

Thanks for any advice guys.


texts: Unity Animation makes object spawn at x0 y0 z0

texts:
I was making an animation for a coin in my game in Unity, and when I was testing the full game, I saw that the coin is spawning at x0 y0 z0 and is doing the animation there.
Then I realized that it was the animation, that increases and decreases y position and y rotation, starting at 0.
So, I need to make the animation, that increases and decreases position y and rotation y, without affecting the actual position, because it will be different the position of the coins each time.
In a while I will upload a screenshot for describing better the problem.
Any clue?


texts: Rotating a 4D matrix about the Y axis with an X-Z vector

texts:
I should mention that I'm pretty new to Matrices and will probably need a layman's answer to my question.

I have a 4D matrix which represents the rotation of an object in 3D space. I have a normalized 2D vector which represents the direction i want the object to be facing by rotating the Y axis.

I need to be able to change the Y axis rotation of the object only, by applying some sort of calculation to the XZ vector i have. What do i need to do to make this work? And if possible, can any answers come with an explanation of the process so that i can do it again on my own in the future!


texts:
I am building a 2D game using sprites. I'd like to use the z-buffer to aid with shading.

For that I need Unity to write only opaque pixels to the z-buffer (aka depth buffer). In Unity, sprites are built up of polygons, and it is writing these entire polygons, including the transparent pixels, to the depth buffer.

This is the shader I'm using (with some junk added while trying to get this to work) http://pastebin.com/khprCUA0

I have tried

AlphaTest Greater 0
alphatest:MyAlphaTestVar
the discard keyword
Cg's clip function
I suspected that a lighting pass might be writing the depths so I added novertexlights and noambient

I would suspect that AlphaTest prevents transparent pixels from having any effect on the frame or depth buffer (as suggested here), but they still do write to the depth buffer!

The screenshot below shows the inaccurate shapes of objects in the Z-buffer. The king and tree have become blobs because even their transparent pixels were updated in the Z-buffer (drawn using http://willychyr.com/2013/11/unity-shaders-depth-and-normal-textures/):

Compare this to the "correct" shape of the objects in the regular view:

How do I get Unity to not write transparent pixels to the z-buffer?

EDIT:

Unity 5's frame debugger is turning out to be a miracle! Turns out the "Depth Texture" is actually rendered in a separate pass before all other geometry. And I'm having trouble finding out how to use RenderType to include/exclude certain objects from this pass.


texts: How to detect RayHit on part of model and not entire model

texts:
I'm building a low poly role playing Hack and Slash game. When I click it renders a sprite & character moves to that location(with RayCast).

But in this case. I don't want the click to occur on side of the bridge. Clicks should only occur in green coloured part & not in the red part. How should I fix this problem?


texts: Having some trouble with my frustum checking code

texts:
I'm trying to check if a bounding sphere is either within or intersecting my frustum. It mostly works but there are cases where it should and it doesn't. The frustum is made up of 6 planes which have a position, direction and normal vector. Sphere has a center and radius value. The frustum is created from translating the mouse coordinates into 3d. If anyone can point me in the right direction it would be greatly appreciated. I'm not great at Maths either.

static float DistanceFromPointToPlane(Plane p, DirectX::SimpleMath::Vector3 point) {
    float distance = p.normal.Dot(point - p.position);

    return distance;
}

static bool IsSphereInsidePlane(DirectX::SimpleMath::Vector3 sphereCentre, Plane p, float radius) {
    float d = DistanceFromPointToPlane(p, sphereCentre);
    return -d > radius;
}

static bool SphereIntersectsPlane(DirectX::SimpleMath::Vector3 sphereCentre, Plane p, float radius) {
        return fabs(DistanceFromPointToPlane(p, sphereCentre)) <= radius;
    }


texts: Cannot explicitly hide variable member even using "new" keyword

texts:
See the answer by me, this problem is pretty much my own mistakes of miss understandings.

So, here is my problem.

I have parent class called CameraBehaviour derived from MonoBehaviour

public class CameraBehaviour : MonoBehaviour
{
    public MinMax CameraViewRange;

    private Single CalculateViewRange() { ... }
}

and have two class ActionCamera2D and ActionCamera3D derived from CameraBehaviour

public class ActionCamera2D : CameraBehaviour
{
    [MinMaxRange (2f, 5f)]
    public new MinMax CameraViewRange = new MinMax(2f, 5f);
}

public class ActionCamera3D : CameraBehaviour
{
    [MinMaxRange(20f, 50f)]
    public new MinMax CameraViewRange = new MinMax(20f, 50f);
}

as you can see, both the script has CameraViewRange with new keyword and has different MinMaxRange attribute attached on each script, so the limit is will be vary between this script but still using the same CalculateViewRange calculation as the parent script.

But it turns out to be not possible, in Unity at least, raising an error:

The same field name is serialized multiple times in the class or its parent class.
This is not supported: Base(MonoBehaviour) CameraViewRange

MinMaxRange is a custom written attribute for property drawer.
MinMax is a custom struct that store min and max value.

  So, how can I overcome / deal with this problem ?
  No, you can't, it's the C# design pattern to prevent that.

  Is my code pattern here is wrong ?
  Yes.

  Is there any workaround or better solutions for this ?
  See the answer by me.

  Or is this the C# and Unity limitations ?
  It's just the C# and Unity Inspector design pattern.

thanks


texts:
I have an existing depth texture and some other color textures, and want to process the information in them by rendering to a 3D texture (based on the depth contained in the depth texture, i.e. a point at (x/y) in the depth texture will be rendered to (x/y/texture(depth,uv)) in the 3D texture).

Simply doing one manual draw call for each slice of the 3D texture (via glFramebufferTextureLayer) is terribly slow, since I don't know beforehand to what slice of the 3D texture a given texel from one of the color textures or the depth texture belongs. This means the entire process is effectively

for each slice
  for each texel in depth texture
      process color textures and render to slice

So I have to sample the depth texture completely per each slice, and I also have to go through the processing (at least until to discard;) for all texels in it.

It would be much faster if I could rearrange the process to

for each texel in depth texture
   figure out what slice it should end up in
       process color textures and render to slice

Is this possible? If so, how?

What I'm actually trying to do: the color textures contain lighting information (as seen from light view, it's a reflective shadow map). I want to accumulate that information in the 3D texture and then later use it to light the scene. More specifically I'm trying to implement Cryteks Light Propagation Volumes algorithm.


texts: How do I employ an arcball to allow the user to look around the screen?

texts:
How do I apply an arcball (using quaternions) along with mouse events, to allow the user to look around the screen using the o3d WebGL framework?

This sample uses the arcball for rotating the transform of an "object," but rather than apply this to a transform, I would like to apply the rotation to the camera's target, to create a first person style ability to look around the scene, as if the camera is inside the centre of the arcball instead of rotating from the outside.

The code that is used in this sample is

var rotationQuat = g_aball.drag([e.x, e.y]);
var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);

The code that I am using which doesn't work

var rotationQuat = g_aball.drag([e.x, e.y]);
var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);

var cameraRotationMatrix4 = g_math.matrix4.lookAt(
  g_eye, g_target, [g_up[0], g_up[1] * -1, g_up[2]]
);
var cameraRotation = g_math.matrix4.setUpper3x3(
  cameraRotationMatrix4, g_thisRot
);
g_target = g_math.addVector(cameraRotation, g_target);

where am I going wrong?


texts: Should scripts interact with an abstraction of the engine?

texts:
I'm using Java and Jython, and after some research I discovered giving scripts direct access to the engine interface could be a mistake, as it would tightly couple the two.

It looks like most scripting that allows mods to create and manage entities does so through some sort of abstraction. Are these abstractions there for this reason, or is it just to provide a more intuitive way for non-programmers to mod the game?


texts: Making a 2D Game: Figuring out sprite sizes?

texts:
I'm currently making a 2D game as a school project using Game Maker and its language. My concern however is around the spriting and art...

I can't figure out how to correctly size everything so it shows up correctly on the end product.
I originally used a temporary 32x32 character but it looks very small when I have the "Room Size" in Game Maker set to 720p...

Is this something that I need to change size-wise on Game Maker, such as changing how far in the perspective/camera is, or do I have to set actual dimension rules? I'm unsure of how to do this properly.


texts:
I'm working in Unity and have created some low poly meshes using blender. Currently, the meshes look good, but the ground seems very lacking. I am not sure how to make it feel natural or even look good in general.

Here is a current image

The ground needs to remain mostly flat due to the game placing flat objects on the top of the plane and the image shows the exact camera angle we are using. But, as you can see in the image, the ground is extremely lacking and it doesn't look like a ground but instead just a flat background color. I've tried textures but it does not look good with the trees and low poly design.

How can I make the ground look better?


texts:
I want a system, where a tank moves and rotates based on the speeds I give him for the two tracks, for example, if I give the left track a speed of 1 and the right one a speed of -1, then I want the tank to stay still and rotate right, while if I give the left track 1 and the right track -0.5, I want it to rotate, but at the same time move forward

Of course the speeds will be between -1 and 1


texts:
If one wants to use services, they can use the ones built in to XNA (Game.Services) and pass around the Game object to everything that needs to either query for a service or add a service.

Alternatively, one can create their own game services class and make it static to avoid having to pass around Game everywhere.

Instead of just passing Game to everything, just to query the services (a code smell already in my opinion, just pass the services) seems a bit silly to me. Instead of passing it everywhere, why not just make a public static GameServices class?

What are the advantages and disadvantages of each approach? Which do you normally opt for?


texts: Unity 2D Sprite Bending between Hinge Joints

texts:
I've created a tentacle that consists of multiple game objects, each attached to eachother using HingeJoint2D's. Gameplay wise this multiple segmented approach is great because I can use Unity's built-in physics, but it doesn't look very good art wise.

Is it possible to 'bend' 2D sprites, so the tentacle segments look like they're attached to eachother? Or perhaps take a single image and bend it using splines of some sort?

I would prefer to keep using multiple game objects to represent the tentacle.


texts:
There have been two instances from the past two weeks that I've heard from well known successful game developers that they use spreadsheets when designing games.

The first being David Whatley in this GDCVault video: From Zero to Time Magazine: App Success

The second being the guys that do Walled Garden Weekly.

David said he models everything out and uses excel models to see how everything plays out. What on earth is he talking about? Is it seeing how the game mechanics react to each other?

Is there somewhere where I can learn more about how to do this?


texts: Unity - Basic AI Enemy Follows Player - Prevent Flocking Of Enemies Together

texts:
I'm in the process of implementing a 2D top-down shooter game. I have a basic AI script that allows enemies to follow the player around. Currently it works fine for one enemy, but as soon as there are multiple enemies, overtime they tend to flock together. How would I go about fixing this issue? I think that one possible solution would be to make the enemies move in a random direction every few frames, but I'm not sure on this.

Below is my C# Script that I am currently using.

using UnityEngine;
using System.Collections;

public class AIScript : MonoBehaviour
{
    public Transform target;
    public int moveSpeed;
    public int rotationSpeed;

    void Start()
    {
        target = GameObject.Find("Michael").transform;
    }

    void Update()
    {
        if (target != null)
        {
            Vector3 dir = target.position - transform.position;
            // Only needed if objects don't share 'z' value.
            dir.z = 0.0f;
            if (dir != Vector3.zero)
                transform.rotation = Quaternion.Slerp ( transform.rotation,
                    Quaternion.FromToRotation (Vector3.right, dir),
                    rotationSpeed * Time.deltaTime);

            //Move Towards Target
            transform.position += (target.position - transform.position).normalized
                * moveSpeed * Time.deltaTime;
        }
        rigidbody2D.velocity = Vector3.zero;
    }
}


texts: I was trying to create IK constraint following a Nathan Vegdahl tutorial, and everything was nice and shiny, until i tried to actually move a bone. It's not moving, only rotating. I see that transform lock panel on location is grey and completly locked, and i have no idea what's wrong.


texts:
Im trying to display a mesh in front of the camera and FACING the camera ( I'm developing an small editor in wpf using helix3d).

Pretty much something like this question

I load my mesh into a ModelVisual3D and I set it 20 units in front of the camera with this code:

var camera = ((PerspectiveCamera) viewport.Camera);
var distanceFromCamera = 20;

var direction = camera.LookDirection;
direction.Normalize();
direction = direction * distanceFromCamera;

var meshPosition = camera.Position + direction;

 var compositeTransform = new Transform3DGroup();

 compositeTransform.Children.Add(new RotationTransform(???));
 compositeTransform.Children.Add(new TranslateTransform3D(meshPosition));

ModelVisual3D mesh = LoadMesh(...);
mesh.Transform = compositeTransform

It already shows correctly in front of the camera, but I'm missing the rotation, how can I extract the rotation of the camera and set it to my mesh so is facing the camera?

Edit

I tried to use the following function to get the rotation matrix but is not working either:

    static Matrix3D CalculateLookAt(Vector3D eye, Vector3D at, Vector3D up)
    {
        if (Math.Abs(up.Length - 0.0) < double.Epsilon) up = new Vector3D(0, 1, 0);
        var zaxis = (at - eye);
        zaxis.Normalize();
        var xaxis = Vector3D.CrossProduct(up, zaxis);
        xaxis.Normalize();
        var yaxis = Vector3D.CrossProduct(zaxis, xaxis);

        return new Matrix3D(
            xaxis.X, yaxis.X, zaxis.X, 0,
            xaxis.Y, yaxis.Y, zaxis.Y, 0,
            xaxis.Z, yaxis.Z, zaxis.Z, 0,
            Vector3D.DotProduct(xaxis, -eye), Vector3D.DotProduct(yaxis, -eye), Vector3D.DotProduct(zaxis, -eye), 1
            );
    }


texts: I'm trying to make a game with cool soundtracks from a bunch of artists. I've made a few playlists in Soundcloud (soundcloud.com) and am trying to get those to play inside of Unity 3d. Is it possible to do that? I can get a mp3 url from the api but then how do I play it? I'm planning to mac and windows. Please help, thanks! <3


texts: LWJGL Determining whether or not a polygon is on-screen

texts:
Not sure whether this is an LWJGL or math question. I want to check whether a shape is on-screen, so that I don't have to render it if it isn't. First of all, is there any simple way to do this that I am overlooking? Like some method or something that I haven't found? I'm going to assume there isn't.

I tried using my trigonometry skills, but it is hard to do this because of how glRotate also distorts the image a little for perspective and realism. Or, is there any way to easily determine if a ray starting from the camera, and going outward in a straight line intersects a shape? (I can probably do it with my math skillz, but is there an easier way?)

By the way, I can easily determine the angle at which the camera is facing around the x and y axis.

EDIT: Or, possibly, I could get the angles of a vector from the camera to the object, and compare those angles to my camera angles. But I have a feeling that the distorts from glRotate and glTranslate would be an issue. I'll try it though.


texts:
I'm trying to recreate a rhythm game. However trying to get the key-presses with SDL2 I ran into the problem, that you can only get an event every time a frame has been successfully rendered (I can't poll the events from another thread than the main thread). As you could separate game-logic from rendering, I thought I could run the game logic (including the polling of the events) for every 1ms and render the screen for every 16ms (60fps).

I read some articles stating that it doesn't make much sense to use multi-threading for that usage, but 16ms are quite a lot of latency for a rhythm game (which has about 30ms to determine a better rating for a better high-score).
(The problem is also described here: Accuracy and frame-rate in a rhythm game)

EDIT: Here It's being said that multi-threading shouldn't be used:

What is the best way to handle event with SDL/C++

Now my question is:"Should I really not separate game-logic from render logic, as I don't need visual feedback for this kind of game and accuracy is more important"


texts: Xna, after mouse click cpu usage goes 100%

texts:
Hi i have following code and it is enough just if i click on blue window then cpu goes to 100% for like at least one minute even with my i7 4 cores. I just check even with empty project and is the same !!!

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    private Texture2D cursorTex;
    private Vector2 cursorPos;
    GraphicsDevice device;

    float xPosition;
    float yPosition;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);

        Content.RootDirectory = "Content";

    }

    protected override void Initialize()
    {
        Viewport vp = GraphicsDevice.Viewport;

        xPosition = vp.X + (vp.Width / 2);
        yPosition = vp.Y + (vp.Height / 2);
        device = graphics.GraphicsDevice;
        base.Initialize();
    }

    protected override void LoadContent()
    {

        spriteBatch = new SpriteBatch(GraphicsDevice);
        cursorTex = Content.Load<Texture2D>("strzalka");
    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {

        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(cursorTex, cursorPos, Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }
}


texts:
I've been working in 3DSMax for years now and decided to give XNA 4.0 a try.  I've got the majority of it working, however the camera is being a pain to me and I can't discern what's gone wrong.  I followed tutorials up to this point and am branching out into newer things.

Basically for this setup, I have a 'grid' in 3D space (all have a Y-component of 0) with spheres located here and there along the grid (spheres are FBX models from 3DS).  What I'm trying to do is write a quick move command that'll move the camera above and behind one of the objects and then look at it.  By using the keyboard, I can scroll through the list of objects and the camera should immediately jump to the specified position.  However, in practice, the camera ends up in strange places, doesn't look where it's supposed to, and I'm not even sure it's actually moving!

The location of the objects is stored within a class object as a Vector2 (hence the Y/Z swap below), as they are all on the same plane (no Y-axis used).  The following code, in theory, should return the position of the camera, and it's target, based on that class object's position in the world.  m_vPosition is a Vector2 that defines the location of the object.  That vector is defined at creation-time and is in the Translation Matrix for the object.

    public void GetCameraHoverLocation(out Vector3 p_vPos, out Vector3 p_vLook)
    {
        p_vPos = new Vector3(0, 0, 0);
        p_vLook = new Vector3(0, 0, 0);
        // Position should be above and behind
        p_vPos.X = m_vPosition.X;
        p_vPos.Y = 1;
        p_vPos.Z = m_vPosition.Y + 10;

        p_vLook.X = m_vPosition.X;
        p_vLook.Y = 0;
        p_vLook.Z = m_vPosition.Y;
    }

The code to move the camera into position is:

    public void SetCameraPosition(Vector3 p_vPos, Vector3 p_vLookAt)
    {
        m_mViewMatrix = Matrix.CreateLookAt(p_vPos, p_vLookAt, Vector3.Up);
        m_vCameraPos = p_vPos;
        m_vCameraView = p_vLookAt;
    }

The Position and LookAt are stored for later usage.  The ViewMatrix is then given to the shader and bob's your uncle.  However, again, the positioning of the camera is alllll wrong.  I'm thinking it might be a complete misunderstanding of the Matrix.CreateLookAt function, but it works as written if I don't bother moving it (up to this point that is).  Can anyone point me in the right direction on this one?  I'm used to the way 3DS does things with cameras (vector for location, vector for target), so that might be polluting my thought process.


texts: Does Blitz3D use its own 3D engine or does it wrap OpenGL?

texts: How does Blitz3D work? I mean internally, does it use OpenGL with basic wrappers or it using some open source 3D engine that itself wraps OpenGL?


texts: Is there an easy way to add TMX Object Layer to a Scene in Andengine?

texts: I have a TMX file with a MAP layer and Object layer (called decorations, with property type = "decorations"). Is there an easy way to add the whole layer to the scene with all objects? Or do I have to iterate through objects and add them one by one?


texts:
I am working on a live wallpaper with Libgdx .
I am wondering if I can give neon glow to my textures , at runtime .
Is this possible? If yes can anybody give me any pointers?


texts: What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8?

texts:
I know this is a potential dupe of this question, but the last answer there was 18 months ago and a lot has happened since.

There seems to be some uncertainty about XNA in Windows 8. Specifically, Windows 8 by default uses the Metro interface, which is not supported by XNA. Also the Windows 8 store will not stock non-metro apps, so it will not stock XNA apps.

Should we stick with XNA or does Microsoft want us to move to a different framework for managed game development in Windows 8?

Edit: As pointed out in one of the comments, Windows 8 will be able to run XNA games in a backward compatibility mode. But that smells of deprecation.


texts: I am working on a game and would like to include a few jump scares. So here is a rather simple question — What makes a good jump scare and when and how should they happen?


texts: The size of the .apk file built by Unity is larger than I expected. Is it image resolution, number of scenes, or something else?


texts: Hi I am searching for an open library (preferred in java) to generate user icons / badges for representing an user in an mmpg, rather than by his player name. The user does not need to take any actions to manipulate the icon by him self, but the system is auto generating the icon when the user is registering. Is there any library / script out there to achieve that? Thanks!


texts:
I'm making a race circuit which is constructed using various textures.

To provide some background, I'm writing it in C++ and creating quads with OpenGL to which I assign a loaded .raw texture too. Currently I use 23 500px x 500px textures of which are all loaded and freed individually.

I have now combined them all into a single sprite/tile sheet making it 3000 x 2000 pixels seems the number of textures/tiles I'm using is increasing.

Now I'm wondering if it's more efficient to load them individually or write extra code to extract a certain tile from the sheet?

Is it better to load the sheet, then extract 23 tiles and store them from one sheet, or load the sheet each time and crop it to the correct tile?

There seems to be a number of way to implement it...

Thanks in advance.


texts:
Looking for options on this, but I wanted to take a Quad (or other shape), apply a material to it, and have it cutout an entire layer, to reveal the layers below/behind it. Sort of like a portal effect.

What's the best option for this?

(This is for 2D)


texts: How to change application surface size without changing view size? (GMS2)

texts:
I am working on a pixel art project in GameMaker 2 with native resolution 428x240. In order to enable "subpixel" rending, I am trying to increase the resolution of my application_surface, but keep my view at its native resolution.

I am trying to increase the resolution of my application_surface by two, but keep my view at the native resolution. I have tried a few different things, but no matter what I do, I can't get it to work consistently.

Here is what I tried most recently:

surface_resize(application_surface, native_width * 2, native_height * 2);
camera_set_view_size(view_camera[0], native_width, native_height);

This works, but when I change rooms, the view resets to the size of the application surface, resulting in something like this:

It seems like every time you change rooms, the view size gets reset to the size of the application surface.

I tried iterating through all rooms and setting their view size to my native resolution on launch, but it doesn't seem to help.

How can I prevent the view from changing sizes on room change? I want to lock it at my native resolution.


texts:
Currently I'm developing a PC game using Unity

Usually on PC games we found graphic/video settings due to varying hardware installed and limitation. Just as in the title, how does a game set its default graphic setting? What parameters do I need to take into account for defining my default graphic setting? Or does the game detect installed hardware capability and programatically enable/disable graphic effects?

AFAIK, most of the time when I tried to play some AAA games with minimum system requirement after installation, the game would be laggy because of some effects like ambient occlusion, high quality texture, and stuff are enabled. So I'm sure the default setting is not the lowest/worst graphic setting available.


texts: Puzzle game: clipping of non-convex polygons on the figures

texts:
I have an original figure in the SVG file. I need to break it randomly on parts, an example of which is specified below:
I have an idea, to use for partitioning Voronoi diagram (Fortune's algorithm). Can I then change the line of intersection of figures to give them a curvature? Can be obtained to identify each shape as a path?
To create a game I'll be using cocos2d-x.


texts: Are there any advantages of Vulkan using traditional methods?

texts:
I keep hearing that Vulkan meant for direct low level operations with the GPU and hence it's targeted toward expert and experienced graphics programmers.

What would be some other advantages of Vulkan that are usable for a more traditional graphics programmer, rather than a full blown AAA expert?

One advantage I keep hearing about is multi-threading support. It's buzzing in media to annoying levels, yet still never explained what and how it's different from OpenGL's level of multi-threading.


texts: How to maintain char widths of non-monospace fonts?

texts:
Having a font via spritesheet (as PNG), the easiest way to render fonts from that is just showing chars as monospace, but as you can imagine, that looks not pretty with chars like l, i, : and so on..

Is there a slick way to maintain the width of every char?

I already thought of storing it into an extra file, telling the width of each char in pixels.

Pro: Fast rendering.
Con: That's one load of work for about 100 chars.

I gave "counting" the pixel-width of each char on rendering it a thought.

Pro: Once that algorithm does it's job there's no work with that afterwards.
Con: As there is pretty much font-rendering going on each frame, this is plain bullshit - performancewise.

I'm open to suggestions and/or known algorithms for this problem.

EDIT: TTF or some other real font is not an option, because they render wayy to pixelated on the small sizes needed.

EDIT: Thanks to lorenzo-gatti, made simple marker-pixels in the spritesheet like so:

Distance between these gets counted on startup of the game and the markers are replaced with transparent pixels. So no heavy additional logic in render which would slow down and startup-time is not really slower than before, thanks!


texts: Positioning partials of character sprite animations

texts:
I'm not entirely sure how to best explain what I'm doing. Maybe I'm going about this completely the wrong way. If any of you find that that is in fact the case, I would appreciate it if you told me how I can do this better.

I've started looking into game development about a week ago and came across a cross-platform framework called LibGDX. So I started working on a practice project which is an incremental game. I'm using the sprites supplied by a program called BannedStory. I want every part of the player's body to be customizable. That means that I'm using every sprite's animations separately.

This is a snippet of code to illustrate how I'm building the character right now.

float playerScreenWidth = HackerStory.WORLD_WIDTH;
    float playerScreenHeight = HackerStory.WORLD_HEIGHT;

    float playerPositionX = playerScreenWidth*0.3f;
    float playerPositionY = playerScreenHeight*0.7f;

    manager = new AssetManager();

    textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/body/light/walking.atlas"));

    bodyAnimation = new Animation(0.25f , textureAtlas.getRegions()); // textureAtlas.getRegions()
    bodyAnimationActor = new AnimatedImage(bodyAnimation);
    bodyAnimationActor.setPosition(playerPositionX, playerPositionY);

    float bodyWidth = bodyAnimation.getKeyFrame(0).getRegionWidth();
    float bodyHeight = bodyAnimation.getKeyFrame(0).getRegionHeight();
    float bodyX = bodyAnimationActor.getX();
    float bodyY = bodyAnimationActor.getY();

    Group body = new Group();
    body.addActor(bodyAnimationActor);

    Group head = new Group();

    textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/head/light/walking.atlas"));

    headAnimation = new Animation(0.25f , textureAtlas.getRegions()); // textureAtlas.getRegions()
    headAnimationActor = new AnimatedImage(headAnimation);
    headAnimationActor.setPosition(bodyX - bodyWidth * 0.05f, bodyY + bodyHeight * 0.87f);

    float headWidth = headAnimation.getKeyFrame(0).getRegionHeight();
    float headHeight = headAnimation.getKeyFrame(0).getRegionHeight();
    float headX = headAnimationActor.getX();
    float headY = headAnimationActor.getY();

    head.addActor(headAnimationActor);

    textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/face/male/002/walking.atlas"));

    faceAnimation = new Animation(0.25f, textureAtlas.getRegions());
    faceAnimationActor = new AnimatedImage(faceAnimation);
    faceAnimationActor.setPosition(headX+headWidth*0.25f, headY + headHeight*0.1f);

    head.addActor(faceAnimationActor);

    textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/hair/male/003/black/walking.atlas"));

    hairAnimation = new Animation(0.25f, textureAtlas.getRegions());
    hairAnimationActor = new AnimatedImage(hairAnimation);
    hairAnimationActor.setPosition(/*headX+headWidth*0.085f*/headX+hairAnimation.getKeyFrame(0).getRegionWidth()*0.04f, headY + headHeight*0.39f);

    head.addActor(hairAnimationActor);

    Group player = new Group();
    player.addActor(body);
    player.addActor(head);

As you can see, I am currently setting the X position for (for example the hair) by using its parent's X co-ordinate plus a fraction of its own width. However, this causes issues when the hair is different widths. What works for one hair sprite, won't work for another.

This is what the previous code results in: http://imgur.com/a/ogP5K

I am at a loss for where to go next. I also couldn't find anything on the subject in other questions, so again, I might be completely wrong in my approach to this.

Does anyone have any idea as to how I could solve this issue?


texts: How to calculate a score algorithm based on elapsed time?

texts:
I'm trying to calculate an alogirthm based on elapsed time to calculate score based on a music beat.
I have the music beat divided into 4 because that's the time measure of that beat.
So If the user presses the correct key at the third beat, which is of course when the perfect beat would be, I'd like it to obtain the best score.
I've tried doing this:

score=percent(bpmt.elapsed,bpm/3);
int scoref(int int1,int int2) {
return int1*100/int2;
}

bpmt.elapsed being how much time was elapsed between the start of that beat and the time that the user  pressed the key and bpm being the total number of milliseconds of that particular beat.

Can anyone tell me a better way to do this please? I think it requires more advanced math and it's kind of beyond me.


texts:
When a character collides with an object in my game, there is a slow motion effect. That's coool, but how would I zoom into a sprite when it collides with another object?

Here is my code currently...

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

public class GameManager : MonoBehaviour
{
    public float slowness = 2f;

    public int index;

    private AudioSource hitSource;

    public Vector3[] Target;
    public Camera Cam;
    public float Speed = 0.012f;

    public void Start()
    {
        Cam = Camera.main;

    }

    public void EndGame()
    {
        Application.targetFrameRate = 300;

        StartCoroutine(RestartLevel());

        hitSource = GetComponent<AudioSource>();

    }

    IEnumerator RestartLevel()
    {
        Cam.orthographicSize = Mathf.Lerp(Cam.orthographicSize, 3, Speed);
        Cam.transform.position = Vector3.Lerp(Cam.transform.position, Target[1], Speed);

        Time.timeScale = 1f / slowness;

        Time.fixedDeltaTime = Time.fixedDeltaTime / slowness;

           yield return new WaitForSeconds(1.5f/slowness);

        Time.timeScale = 1f;
        Time.fixedDeltaTime = Time.fixedDeltaTime * slowness;

        SceneManager.LoadScene(2);

    }

    private void OnCollisionEnter(Collision collision)
    {

    }
}


texts:
I'm trying to create a series of physics-enabled 'ropes', with hard limits on how far they can swing left or right. They are comprised of an oRopeRoot kinematic physics object, which generates a certain number of oRopeSections, round little objects, and finally a single oRopeEndSectionto cap it off.

These are connected by revolute joints with restricted angle of movements. Unfortunately, as you can see from this gif, they are all over the shop. I am still learning about physics joints in Gamemaker, and if anybody can look at the code below and see what might be wrong, I'd be very grateful for the learning experience.

oRopeRoot

Density: 0

Restitution: 0

Collision Group: -1

Linear Damping: 0.5

Angular Damping: 0.5

Friction: 1

(Kinematic)

Create Event:

depth = global.ForeignObjectsOnFaceLayer -1
OriginalX = x
OriginalY = y
image_alpha = 1
image_xscale = random_range(0.3,0.7)
image_yscale = image_xscale
GeneratedValues = true
RopeLength = irandom_range(20,30)
SectionsCreated = 0
EndCreated = false
ParentPore = noone

Step Event:

phy_position_x = OriginalX
phy_position_y = OriginalY - mLeftCheekFurArea.Difference

if SectionsCreated < (RopeLength - 1) {
CreateAndAttachSection()
SectionsCreated = SectionsCreated + 1
} else if SectionsCreated >= (RopeLength - 1) {
if EndCreated = false {
CreateAndAttachEndSection()
EndCreated = true
}
}

CreateAndAttachSection()

if SectionsCreated = 0 {

ParentSection = self.id
ChildSection = instance_create(ParentSection.x,ParentSection.y,oRopeSection)
physics_joint_revolute_create(ParentSection, ChildSection, ParentSection.x,ParentSection.y,-45,45,true,0,0,false,false)
ParentSection = ChildSection
ChildSection = noone

} else if SectionsCreated > 0 {
ChildSection = instance_create(ParentSection.x,ParentSection.y + 6,oRopeSection)
physics_joint_revolute_create(ParentSection, ChildSection, ParentSection.x, ParentSection.y + 6,-45,45,true,0,0,false, false)
ParentSection = ChildSection
ChildSection = noone
}

CreateAndAttachEndSection

ChildSection = instance_create(ParentSection.x,ParentSection.y + 6,oEndSection)
physics_joint_revolute_create(ParentSection, ChildSection, ParentSection.x, ParentSection.y + 6, -45, 45, true, 0, 0, false, false)
ParentSection = noone
ChildSection = noone

oRopeSection

Density: 1

Restitution: 0

Collision Group: -1

Linear Damping: 1

Angular Damping: 1

Friction: 1

oEndSection

Density: 1

Restitution: 0

Collision Group: -1

Linear Damping: 0.5

Angular Damping: 0.5

Friction: 1


texts: Unity Editor extension to group scripts attached to an object

texts:
Let us suppose we have a game object which has hundreds of scripts attached. Now out of those hundreds we can pick out groups responsible for a specific functionality. E.g. there are 15 scripts responsible for moving on the ladder, there 20 scripts which control shooting, 10 scripts which control jumping, etc.
Now it becomes hard to navigate all the scripts when you want to see only a specific feature related scripts.
So, what I want to do is to add some kind of grouping separators in my Inspector view, which would separate groups of scripts from each other.
Of course I know about the following improvements:

making the codebase structure reasonable by utilizing folders
placing the scripts close to each other by reordering them in the Inspector view

But still I feel that having the separators would make my life easier.
E.g. as the red lines on screenshot separate script groups, I would like to have something similar in the editor:

I found some documentation related to my question: https://docs.unity3d.com/Manual/editor-PropertyDrawers.html. But it seems that I can only customize the look of a specific script or property, but not the Inspector view. Is it so?


texts:
I'm looking for this kind of effect MINUS the lights and snow (Another problem).

It needs to change depending on the time of year.
Doesn't need snow or city lights.

Now I'm pretty new to shaders (learnt them yesterday in my spare time) but so far I have achieved:

This moves across the screen display light on both sides.

Now I'm completely lost, as to how I can make it seem like a light map I.E. it needs to be more square/sharper (As it's going off the edges) & have the bottom and top times of year.. I though maybe I could pass sphere mesh to the vertex? Or do something with the map-normal. Or maybe use blending with two textures but I've looked around and it looks extremely difficult.

Code I have so far:

Fragment / Pixel shader:

    //attributes from vertex shader
varying vec4 vColor;
varying vec2 vTexCoord;

//our texture samplers
uniform sampler2D u_texture;   //diffuse map
uniform sampler2D u_normals;   //normal map

//values used for shading algorithm...
uniform vec2 Resolution;      //resolution of screen
uniform vec3 LightPos;        //light position, normalized
uniform vec4 LightColor;      //light RGBA -- alpha is intensity
uniform vec4 AmbientColor;    //ambient RGBA -- alpha is intensity
uniform vec3 Falloff;         //attenuation coefficients
uniform float lightX;         //X Position of light. Can also feed Y for times of the year.

void main()
{
    //RGBA of our diffuse color
    vec4 DiffuseColor = texture2D(u_texture, vTexCoord);

    //RGB of our normal map
    vec3 NormalMap = texture2D(u_normals, vTexCoord).rgb;

    int numberOfLights = 3;
    vec3 lightPoses[3];
    vec3 lightDirections[3];
    //LightX goes to 0, then back to 1.
    lightPoses[0] = vec3(lightX - 1.0, LightPos.y, LightPos.z);
    lightPoses[1] = vec3(lightX, LightPos.y, LightPos.z);
    lightPoses[2] = vec3(lightX + 1.0, LightPos.y, LightPos.z);

    //TODO Introduce one extra light for top and bottom. OR Figure out how to squash the Y.
    //TODO Needs to be sharper light.

    vec3 Sum = vec3(0.0);

    //Go though both lights.
    for(int index=0; index < numberOfLights; index++)
    {
        //The delta position of light
        vec3 LightDir = vec3(lightPoses[index].xy - (gl_FragCoord.xy / Resolution.xy), LightPos.z);

        //Correct for aspect ratio
        LightDir.x = LightDir.x * (Resolution.x / Resolution.y);

        //Make it bigger. (smaller the value the bigger.)
        LightDir *= vec3(0.55, 0.4, 1.0);

        //Determine distance (used for attenuation) BEFORE we normalize our LightDir
        float D = length(LightDir);

        //normalize our vectors
        vec3 N = normalize(NormalMap * 2.0 - 1.0);
        vec3 L = normalize(LightDir);

        //Pre-multiply light color with intensity
        //Then perform "N dot L" to determine our diffuse term
        vec3 Diffuse = (LightColor.rgb * LightColor.a) * max(dot(N, L), 0.0);

        //pre-multiply ambient color with intensity
        vec3 Ambient = AmbientColor.rgb * AmbientColor.a;
        //Because there are more lights, take off total ambient power.
        Ambient *= vec3(1.0 / float(numberOfLights));

        //Calculate attenuation (The amount of fade the light has.)
        float Attenuation = 1.0 / (Falloff.x + (Falloff.y*D) + (Falloff.z*D*D));

        //the calculation which brings it all together
        vec3 Intensity = Ambient + Diffuse * Attenuation;

        vec3 FinalColor = DiffuseColor.rgb * Intensity;

        Sum += FinalColor;
    }

    gl_FragColor = vec4(Sum, DiffuseColor.a);
}

Vertex Shader:

//combined projection and view matrix
uniform mat4 u_projTrans;

//"in" attributes from our SpriteBatch
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

//"out" varyings to our fragment shader
varying vec4 vColor;
varying vec2 vTexCoord;

void main() {
    vColor = a_color;
    vTexCoord = a_texCoord0;
    gl_Position = u_projTrans * a_position;
}


texts: Maximum audio delay before the player notices?

texts: Given some event in a game, what is the maximum delay to producing audio that the player will properly associate the audio with that event (and not perceive lag)?


texts:
I'm currently working on 3D project (C++) and I have now come to writing the collision detection systems.

Basically my question is regarding how to architect it.

All the collisions are either between AABB-AABB or AABB-circle.  I'm perfectly aware how to detect whether any two objects are colliding, but I don't know where to do the checks.

Currently I am trying to make a CollisioManager class that contains a list of all the AABBs in the level and then the player object makes a call to the CollisionManager to ask whether it is currently colliding with any (then acts accordingly).

I think I can do it this way but are there any other ways of organizing it as it feels a bit messy and not the cleanest of solutions.


texts: How to detect and prevent the resolution of fake collisions?

texts:
I'm creating my own physics engine and I came across a small inconvenience. Here how it goes: when a body tries to push into something it really can't push, it gets pushed back (which is completly fine). But when it tries to push that solid plus another simple box, the box gets pushed as if the body has really moved even if it can't.

Here's a visual explanation:

My current collision resolver is solving collisions by altering position of bodies. Here is its pseudo code simplified for the question.

/**
 * Resolves the collision by pushing a body or another
 *
 */
void resolve(Collision collision) {
    float weightA = getWeight(collision.world, collision.bodyA, -collision.normal);
    float weightB = getWeight(collision.world, collision.bodyB, collision.normal);

    //This resolves who gets to push who in a collision
    DynamicBody toPush = weightA > weightB ? collision.bodyB : collision.bodyA

    Vector normal = toPush == collision.bodyA ? -collision.normal : collision.normal;

    float replaceX = normal.x * pene;
    float replaceY = normal.y * pene;

    if(replaceX != 0f) {
        //getCollisionShifting() is the total shifting done by collisions in this frame.
        //When this resolver will be done, it will be added to the position

        float dirX = signum(toPush.getCollisionShifting().x);

        if(!original || dirX != signum(replaceX))
            toPush.getCollisionShifting().x += replaceX;
        else if(dirX == 0 || replaceX * dirX > toPush.getCollisionShifting().x * dirX)
            toPush.getCollisionShifting().x = replaceX;
    }

    /* Here, exactly the same thing is done with Y */
    //...
}

/**
 * This finds the weight of a body based on his own weight plus all the bodies its colliding with in a direction
 *
 * Uses a recursive method
 * This method might not be the best but it works and only becames inefficient for really big stacks of objects
 * Since my game won't include giant stacks, its viable for now
 */
float getWeight(World world, Body body, Vector normal) {
    float weight = body.getWeight();

    for(Collision collision : world.getCollisions()) {
        if(collision.bodyB == body)
            collision = Collision.swap(collision); //turns the collision around so bodyB becomes bodyA

        if(collision.bodyA == body && collision.normal.dot(normal) == 1f)
                weight += getWeight(world, collision.bodyB, normal);
    }

    return weight;
}

I included this code for you to have a better look at my current approach but I do not ask anyone to write the solution into that code. A theoric explanation of a working solution is what I'm looking for.

Currently, collisions aren't solved in any particular order. Will I have to sort the collisions ? I hope not since it would slow down the whole thing just for this. So, how can I fix this issue ?

P.S. : Please note that this physics engine is open source and you can access the original code of this example here.


texts: How do I draw a point sprite using OpenGL ES on Android?

texts:
Edit: I'm using the GL enum, which is incorrect since it's not part of OpenGL ES (see my answer). I should have used GL10, GL11 or GL20 instead.

Here's a few snippets of what I have so far...

void create()
{
    renderer = new ImmediateModeRenderer();

    tiles = Gdx.graphics.newTexture(
        Gdx.files.getFileHandle("res/tiles2.png", FileType.Internal),
        TextureFilter.MipMap,
        TextureFilter.Linear,
        TextureWrap.ClampToEdge,
        TextureWrap.ClampToEdge);
}

void render()
{
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    Gdx.gl.glClearColor(0.6f, 0.7f, 0.9f, 1);
}

void renderSprite()
{
    int handle = tiles.getTextureObjectHandle();
    Gdx.gl.glBindTexture(GL.GL_TEXTURE_2D, handle);
    Gdx.gl.glEnable(GL.GL_POINT_SPRITE);
    Gdx.gl11.glTexEnvi(GL.GL_POINT_SPRITE, GL.GL_COORD_REPLACE, GL.GL_TRUE);

    renderer.begin(GL.GL_POINTS);
    renderer.vertex(pos.x, pos.y, pos.z);
    renderer.end();
}

create() is called once when the program starts, and renderSprites() is called for each sprite (so, pos is unique to each sprite) where the sprites are arranged in a sort-of 3D cube.

Unfortunately though, this just renders a few white dots...

I suppose that the texture isn't being bound which is why I'm getting white dots. Also, when I draw my sprites on anything other than 0 z-axis, they do not appear -- I read that I need to crease my zfar and znear, but I have no idea how to do this using libgdx (perhaps it's because I'm using ortho projection? What do I use instead?).

I know that the texture is usable, since I was able to render it using a SpriteBatch, but  I guess I'm not using it properly with OpenGL.


texts:
VRTK allow collision detection by adding the VRTK_HeadsetCollision, VRTK_BodyPhysics, VRTK_HeadsetFade and VRTK_HeadsetCollisionFade scripts into Unity.

This works so that in VR when I walk through a wall, the scene fades to black as expected.

However, I would also like to trigger events when I enter certain spaces in VR. Usually I would use a Unity BoxCollider with IsTrigger checked, but unfortunately, VRTK seems to ignore the IsTrigger value as it still fades to black when I enter the "zone".

How can I trigger a Unity event when the VR player enter's a zone with VRTK?


texts: Should the networking of my game be a component or a service?

texts:
I am working on a windows game and I am trying to understand the  XNA GameComponents and GameServices classes and use. From what I understand about a component is that it has an Update method that gets call in every frame, and a service can be referenced from other components if needed.

So the way I think a network component would work is that in its Update method it would receive and send data. It probably makes sense to receive the network data once per frame, but it doesn't for sending it. Shouldn't the game send its own updates to others the moment it has it to cut down on lag?


texts: network programming: simultaneous IO over sockets?

texts:
In my curses based game, I decided to add multiplayer functionality over net, in addition to one-keyboard mulitiplayer game. I use switch loop and in case it's 1st user's buttons,
user 1 is acting appropriately and second otherwise, without blocking each other's movements i.e not waiting for opponents move.
Now I read socket tutorials, and use server looking like this:

wait for 1st user to connect
wait for 2nd user to connect

loop:
read from 1st
write to 2nd
read from 2nd
write to 1st

Now problem is obvious, players would block each others movements, how this network multiplayer problems solved in games design?


texts: How AlphaBlend Blendstate works in XNA 4 when accumulighting light into a RenderTarget?

texts:
I am using a Deferred Rendering engine from Catalin Zima's tutorial:

His lighting shader returns the color of the light in the rgb channels and the specular component in the alpha channel. Here is how light gets accumulated:

Game.GraphicsDevice.SetRenderTarget(LightRT);

Game.GraphicsDevice.Clear(Color.Transparent);

Game.GraphicsDevice.BlendState = BlendState.AlphaBlend;

// Continuously draw 3d spheres with lighting pixel shader.
...

Game.GraphicsDevice.BlendState = BlendState.Opaque;

MSDN states that AlphaBlend field of the BlendState class uses the next formula for alphablending:

(source × Blend.SourceAlpha) + (destination × Blend.InvSourceAlpha),

where "source" is the color of the pixel returned by the shader and "destination" is the color of the pixel in the rendertarget.

My question is why do my colors are accumulated correctly in the Light rendertarget even when the new pixels' alphas equal zero? As a quick sanity check I ran the following code in the light's pixel shader:

float specularLight = 0;

float4 light4 = attenuation * lightIntensity * float4(diffuseLight.rgb,specularLight);

if (light4.a == 0)
light4 = 0;

return light4;

This prevents lighting from getting accumulated and, subsequently, drawn on the screen. But when I do the following:

float specularLight = 0;

float4 light4 = attenuation * lightIntensity * float4(diffuseLight.rgb,specularLight);

return light4;

The light is accumulated and drawn exactly where it needs to be. What am I missing? According to the formula above:

(source x 0) + (destination x 1) should equal destination, so the "LightRT" rendertarget must not change when I draw light spheres into it!

It feels like the GPU is using the Additive blend instead:

(source × Blend.One) + (destination × Blend.One)


texts: Changing distance after some time on OnGUI Unity

texts:
Though I am using IEnumerator to calculate the distance travelled value, the distance is updated very frequently, how can I change that? and why exactly increasing the time in WaitForSeconds function not changing the behaviour?

    void OnGUI ()
    {
        GUI.contentColor = Color.black;
        GUI.Label (new Rect (40, 40, 140, 40), "Speed : " + _speed, "color");
        StartCoroutine (distancetravelled ());
        GUI.Label (new Rect (40, 100, 100, 140), "Dist : " + Mathf.RoundToInt (distance * 1000) + " Kms", "color");

    }

    IEnumerator distancetravelled ()
    {
        timeInHours = (Time.smoothDeltaTime / 60) / 60;
        if(PlayerControl.collision != true)
        distance += _speed * timeInHours;
        yield return new WaitForSeconds (60);
    }


texts: How to mimic the same fixed-size horizon as in this racing game?

texts:
I am trying to replicate the same horizon (buildings and sky) as in the image below:

As you can see, the player has advanced in a straight line, yet the horizon has still the same size:

This is my attempt using 3D, while it's okay when the player is on the start line:

It's not so great when the player advanced as much as in the image no. 2:

This is an overview of where the horizon buildings and sky are located:

Obviously this won't achieve such effect when one is close to it, so I've tried to scale up the horizon on all axes but the problem is that the buildings are too small depending where you look at them from.

How can one mimic such rendering ?


texts: Creating a WARP device in managed DirectX

texts:
I have a very old graphic card that only supports shader model 2, but I need shader model 3 or up for the app I am developing. I tried to use a reference device but it seems to run very slowly, then I found some samples in C++ that allows me to change to a WARP device and the performance is good. I am using C# and I don't know how to create such type of device.
So the question is: how do I create a WARP device in C#?
Thanks in advance.


texts: directx render order / alpha blend rendering

texts:
I have a question about how to proper render 3d objects in a good order.
I use blend states to render some 3d models with a transparent texture.
This works but if there are multiple alpha objects in the scene it gets messed up because of the seemingly random render order.

Now I ask myself how should I do it?

The first theory I have in mind would be:
When I render something I actually don't render it, I just save it in some sort of queue and sort it later at the final end call (expensive because I have to allocate / deallocate memory a lot and sort).

But even with this theory I still dont know how I should sort them.
I cant just look how they are positioned because at some times they are kind of in each other so looking for these values would produce in wrong results.

I already guessed that i have to order in the way the camera is positioned or some way.

Hope you can help me