texts: A good way to build a game loop in OpenGL

texts:
I'm currently beginning to learn OpenGL at school, and I've started making a simple game the other day (on my own, not for school). I'm using freeglut, and am building it in C, so for my game loop I had really just been using a function I made passed to glutIdleFunc to update all the drawing and physics in one pass. This was fine for simple animations that I didn't care too much about the frame rate, but since the game is mostly physics based, I really want to (need to) tie down how fast it's updating.

So my first attempt was to have my function I pass to glutIdleFunc (myIdle()) to keep track of how much time has passed since the previous call to it, and update the physics (and currently graphics) every so many milliseconds. I used timeGetTime() to do this (by using <windows.h>). And this got me to thinking, is using the idle function really a good way of going about the game loop?

My question is, what is a better way to implement the game loop in OpenGL? Should I avoid using the idle function?


texts: What are the basics of 3D triangle/quad sorting?

texts:
I am really curious how any 3D engine or even the GPU sorts triangles and quads. Are they basically taking a "center" point of a particular triangle/quad/poly and then calculate a distance from a camera point?

How is the depth of a polygon calculated if not using a point distance algorithm? Keep in mind I am a complete noob regarding 3D.


texts:
I am having trouble rendering 3D models with monogame.
The problem only occurs when I export the object from blender with two materials on it. Example:

Monogame sees those two different materials and renders them correctly.
Here comes the problem.. When you start moving the object around you can clearly see the edges which are with the snow material dragging or glitching. Image to see what I mean:
As you can see the edges on the bottom with the Stone_Normal material appear ok but the edges with the snow material are glitching. This is only happening when you move the object around and it doesn't have to be fast. In this example, I am just rotating the object around its axis.


texts: How to rotate a 3D instance using an HLSL shader

texts:
I'm experimenting a little with HLSL shaders. I have the following code for a vertex shader, it is used to render a few instances of a 3D model. Let's say I want to rotate these instances on their Y axis, and I want to do it inside the shader, is it possible? I cannot find any documentation about this.

Here it is my code:

UPDATE: I modified the code so that now the shader receives a rotation parameter instanceRotation (in radians) and use the instanceRotation.y to create a matrix to rotate the object instance around the y axis. It looks like it works, I'll leave it here in case anybody needs it.

/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
    float3 instancePosition : TEXCOORD1;
    float3 instanceRotation : TEXCOORD2;

};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};

////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType LightVertexShader(VertexInputType input)
{
PixelInputType output;

// Change the position vector to be 4 units for proper matrix calculations.
input.position.w = 1.0f;

matrix <float, 4, 4> translation =
{
    1.0f, 0.0f, 0.0f, 0.0f,
    0.0f, 1.0f, 0.0f, 0.0f,
    0.0f, 0.0f, 1.0f, 0.0f,
    input.instancePosition.x, input.instancePosition.y, input.instancePosition.z, 1.0f

};

matrix <float, 4, 4> rotationAroundY = {
               cos(input.instanceRotation.y), 0.0f, -sin(input.instanceRotation.y), 0.0f,
               0.0f, 1.0f, 0.0f, 0.0f,
               sin(input.instanceRotation.y), 0.0f, cos(input.instanceRotation.y), 0.0f,
               0.0f, 0.0f, 0.0f, 1.0f
                           };

matrix <float, 4, 4> composition;

//i compose together the rotation around y and the translation, the order is important!
composition = mul(rotationAroundY,translation);
//i apply the transformation to the vertex input.position
output.position = mul(input.position,composition);

// Calculate the position of the vertex against the world, view, and projection matrices.
output.position = mul(output.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);

// Store the texture coordinates for the pixel shader.
output.tex = input.tex;

// Calculate the normal vector against the world matrix only.
output.normal = mul(input.normal, (float3x3)worldMatrix);

// Normalize the normal vector.
output.normal = normalize(output.normal);

return output;

}


texts: How can I attach a libGDX actor to a box2D body?

texts:
I'm creating game like hill climb racing.

I created my car with the help of shapes and joints but I don't know how to attach graphics to it. I used actors and sprites before for the sake of learning, but I don't know how to use those with box2d bodies.

How can I?


texts:
I'm trying to learn how to use Unity for my class composition, and I was wondering if you could help me.

I'm trying to create a simple game where the player is trying to pop a bunch of balloons. However, any given balloon can only be popped if all of its conditions are met. Example conditions are:

The player color must match the balloon color
The balloon must be popped in sequence (balloon A must be popped before balloon C)
The balloon is only pop-able during a certain time window

And I'm sure you could think of more.

Balloons can have 0 to many conditions associated with them, but they follow the 80/20 principle where 80% will fall into a specific category (e.g. color-match-only, or color-and-sequence-only).

My Initial Solution

I created a "Balloon" class that contains a list of "ICondition" interfaces. When a collision occurs, the balloon loops through each condition to determine whether the balloon is pop-able or not. I populate this list within a "BalloonFactory" class. For 80% scenarios I can just pass in the name of the balloon type I want. For 20% scenarios I can pass a list of conditions.
This solution works, except for each new combination I need to change the factory code to include the new condition.

What I'd Like to Do

Instead of storing the balloon definitions in code, I'd prefer to create prefabs in Unity and use the editor to assign condition implementations to each balloon. My problem so far is that the Unity editor doesn't seem to like displaying a list of interfaces or abstract classes.

Is there some way to do what I'm trying to do here? Or is there a third option which you would recommend?


texts:
I'm new here so forgive me if I have some lingo wrong.

I am designing an app for hockey players that trains them in stickhandling skills. The app tracks time you watch videos/do the exercises.

We want to have the players progress through levels (34 levels), so we can celebrate their progress and give them something to chase after. The truth is the more they drill, the better they actually become, so it really benefits them.

My problem is I don't know how to really design the levels. You train by running through a playlist, let's say that's a standard 4 minutes of training (Somewhat high intensity, too). My thought was doing the first playlist gets you the first level, and it's pretty easy through the first 5. Then it gets tougher each 5 levels until the last 4-5 are really difficult.

Is there some kind of formula for this to design it so the levels make sense vs. just guessing? We want them to train and progress through the levels, not being too hard or too easy.


texts: Unintended window opening when pressing Unity's "Submit" button

texts:
I've been working on a top down 2D game for a while now, and yesterday I found a strange bug that I just can't explain to myself whatsoever. I have a loot window for looting enemies, as well as a character panel to equip gear/see stats. I realized that after I open and close a loot window, if I press the space button (used for attacking, not for opening any windows) while holding A/LeftArrow or W/UpArrow it opens the character panel. Once this happens, I can press space to open/close the character panel.

Went to the character panels OpenClose() function (all it does is set the canvas group alpha to 0 and block raycast to false and vice versa) which is being called unintentionally, put a debug.log inside to verify if it really was being called, and yes, it is. I look up all references to see where I used it, but I only use it in a single place in the project that is behind an if-statement looking for they keycode C (NOT space). I added a debug.log for the Input.inputstring to see if somehow a magic C button press is ending up in that function, but no. If I press C to open the window, the debug log pops up, if I press space, the inputstring appears to be empty, so the if statement to get to the only place in the code referencing that function cannot be met. Removed the space button from my Player entirely, the behaviour still persists.

Added another debug.log with stackTrace.GetFrame(1).GetMethod().Name to show who is actually running this function, but it turns out that if I run it and press C, it says it's being opened by the update function in the UIManager (as expected). If I run it the strange, unintended way, it says it is being run by the EventSystems Invoke function. Coupled with the fact that the behaviour persists despite the space button being removed from the player, I realized that it's Unity's built in "Submit" button being pressed.

Strange behaviour:

It appears to call the submit function on the OpenClose button for the character panel, but only under the circumstance that I closed a loot window and haven't clicked the mouse anywhere yet afterwards. If I deactivate the button that holds the character panels OpenClose function, the behaviour stops. The button shouldn't be pressed though, because it is on a canvas group with alpha 0/block raycast=false, just like all the other buttons with the identical function that work fine. The loot window has no idea about the character panel either, and all the windows are properly wired to their own OpenClose function.
Upon further inspection, the window only starts showing up if, after closing a loot window, i press A/LeftArrow+Space or W/UpArrow+Space. This is getting more and more confusing for me.

So basically my issue is; how do I figure out why this function is being called? It feels as if closing the loot window somehow "caches" the OpenClose button for the character panel onto the submit button, but only until I click elsewhere on the screen. Did you guys have any experience with a similar situation? Could you share some pointers on how to debug this? What is the "submit" button usually used for, and what would make it only work in combination with the left/top directional buttons?  I've spent about 4 hours on this now and don't know how to get any further.


texts: Advice on mapping tiles to a height map/3D world

texts:
I've been attempting to think of a way to map tiles to a height map. Where a grid can be either layered or integrated into the world data. However, since I am not using voxels I could use some advice on where to start or look into on doing something like this.

For example a 16x16 grid layout on 3D world data.


texts: Making certain GameObjects visible for a camera

texts:
I have 2 cameras in my 2D game.

One displays gameobjects normally, and the other camera draws some of these gameobjects reflected (scale.y *= -1). The reflected camera would draw only objects in the "Water" layer, and I would change the layer of the GameObjects I want to reflect on the precull and postrender functions. This way I can decide which GameObjects would be reflected, changing the layer on the fly at runtime, which is a requirement.

-Precull: Change the desired GameObjects layer to "water", and apply scale.y*= -1

-OnPostRender:  Change the Gameobjects layer to their original value, and apply scale*= -1

This was working correctly when my objects were simple, but now my objects are more complex, and I can't rely on changing the layer of the gameobjectson the fly, as I can't tell what their original layer was for each part of the object, in order to revert the changes applied during the precull.

Is there anyway to tell a camera which objects should it render besides using the culling mask?


texts: Architecture a for a central renderer rather than self-rendering

texts:
For the architectural side of rendering, there's two main ways: having each object render itself, and having a single renderer which renders everything.

I'm currently aiming for the second idea, for the following reasons:

The list can be sorted to only use shaders once. Else each object would have to bind the shader, because it's not sure if it's active. The objects could be sorted and grouped.
Easier to swap APIs. With a few macro lines, it can be easy to swap between a DirectX renderer and an OpenGL renderer (not a reason for my project, but still a good point)
Easier to manage rendering code

Of course, if anyone has strong recommendations for the first method, I will listen to them.

But I was wondering how make this work.

First idea
The renderer has a list of pointers to the renderable components of each entity, which register themselves on RenderCompoent creation. However, I'm worrying that this may end up as a lot of extra pointer weight. But I can sort the list of pointers every so often.

Second idea
The entire list of entities is passed to the renderer each render call. The renderer then sorts the list (each call, or maybe once?) and gets what it wants. That's a lot of passing and/or sorting, however.

Other ideas
???
PROFIT

Anyone got ideas? Thank you.


texts: How can I return the class as a Transform in the array instead of each property?

texts:
public class TransformInfo
    {
        public string sceneName;
        public string name;
        public Transform parent;
        public Vector3 pos;
        public Quaternion rot;
        public Vector3 scale;
    }

Then the method:

public static TransformInfo[]  LoadTransformInfo()
    {
        string jsonTransform = File.ReadAllText(@"d:\json\json.txt");
        if (jsonTransform == null)
        {
            return null;
        }

        TransformInfo[] savedTransforms = JsonHelper.FromJson<TransformInfo>(jsonTransform);

        return savedTransforms;
    }

The return is:

But then when using it:

var test = TransformSaver.LoadTransformInfo();

Each item in the array contain the the TransfomInfo but instead I want it to return a Transform with already the info.

So I can do for example:

Transform test1 = test[0];

Instead make a loop and assign each property from the Test to the new Transform test1.


texts:
I have simple mechanism for testing of two balls colliding:

private static boolean isColliding(float firstBallX, float firstBallY, double firstBallRadius, float secondBallX, float secondBallY, double secondBallRadius) {
       final double a = firstBallRadius + secondBallRadius;
       final double dx = firstBallX - secondBallX;
       final double dy = firstBallY - secondBallY;
       return a * a > (dx * dx + dy * dy);
   }

And it works great. One of the balls is moving and the other (second one) is static.
I have two questions.

When a collision occurs, how do I change the movement of the first ball (the moving) one to its logical path? I suppose I should change the direction somehow, but cannot figure out how...?

The other question is how do I tell the static ball, after the collision move? And what is its path, direction and staff...?

Thanks in advance.


texts: How can I place my Enchant.js game into a DIV in a fully-designed web site?

texts: Following the Enchant.js tutorial I cannot find a way to define the place the game is rendered in the page. It either takes the maximum possible area or limits itself to the given size (using game.scale = 1).


texts: From a game developing point of view, how important do you consider templates to be as a topic to know about in C++? Have you used templates as a part of developing games or similar? Neither do I really understand how important templates can be considered from a general point of view.


texts: Unity3D How to tell when editor script is added to object

texts:
What I want is a way that an editor script can tell when it has been attached to an object in the scene.

OnEnable() and Awake() only happen when you bring an object with the editor script attached to it up in the inspector.

Is there any built in method to accomplish this? Or perhaps some work around? The editor script only needs to tell when itself has been added to an object, not any other components.


texts: Reconstructing 3D Rotation from 8 byte - Assistence required

texts:
I am currently trying to load 3D models and animations into a program. The file format has no public description, so I am decoding them piece by piece. (I'm studying computer science and it's for educational purposes)

My problem is to restore 3 dimensional rotation from the skeleton files as the rotation is stored in 8 bytes only and I can't figure out how that data represents rotation around 3 axis. This is a sample skeleton with 11 joints:

                                   float |    float |    float             Bytes (hexadecimal values)
Joint  0: Parent: -1 Position: ( 0.000000|  0.000000|  0.000000) Rotation: 00 40 00 40 00 C0 00 C0
Joint  1: Parent:  0 Position: ( 3.042923| -0.000000| -0.085759) Rotation: 00 00 82 5A 00 00 82 5A
Joint  2: Parent:  0 Position: ( 3.803955| -0.000000| -0.085759) Rotation: 00 00 82 5A 00 00 82 5A
Joint  3: Parent:  0 Position: ( 4.482897| -0.000000| -0.085759) Rotation: 00 00 82 5A 00 00 82 5A
Joint  4: Parent:  1 Position: ( 0.824744| -0.000000|  0.000000) Rotation: 00 00 00 00 00 00 FF 7F
Joint  5: Parent:  2 Position: ( 0.694988| -0.000000|  0.000000) Rotation: 00 00 00 00 00 00 FF 7F
Joint  6: Parent:  3 Position: ( 0.509095| -0.000000| -0.000000) Rotation: 00 00 00 00 00 00 FF 7F
Joint  7: Parent:  4 Position: ( 0.609431|  0.000000|  0.000000) Rotation: 00 00 00 00 00 00 FF 7F
Joint  8: Parent:  5 Position: ( 0.609431|  0.000000|  0.000000) Rotation: 00 00 00 00 00 00 FF 7F
Joint  9: Parent:  6 Position: ( 0.609431|  0.000000| -0.000000) Rotation: 00 00 00 00 00 00 FF 7F
Joint 10: Parent:  7 Position: ( 0.842106|  0.000000|  0.000000) Rotation: 00 00 00 00 00 00 FF 7F

which should form roughly this shape:

3-6-9
|
|2-5-8
||
||1-4-7-10
|||
 0

But as you can see, the joints only extend in the 1st dimension (excluding 1, 2 and 3 which do extend a little in the 3rd dimension) so the coordinates have to be relative to the parent (which makes perfectly sense in terms of a skeleton).

My problem is to figure out how the rotation is stored in the 8 bytes per joint.

Short example: joints 1, 2 and 3 have to store a 90° rotation for the skeleton to work ..
I allready did some research for different representations, but none can store arbitrary rotations around 3 axis in only 8 bytes, usually it takes double the space (4 floats) ..


texts: How can I avoid assets reload if an Android activity is re-created?

texts:
I've put my libGDX view inside a bigger Android layout. When the user rotates the screen, a new layout specific for the orientation is drawn, for this reason, the activity is rebuilt from scratch forcing the libGDX view to reload all assets.

I tried to store these assets in a static variable, but on the second time I create the libGDX view, they are not rendered correctly (it looks like textures are not loaded and everything is transparent).

How can I avoid reloading heavy assets (models and textures)?


texts:
I am trying to implement a class Sphere in C++.

Therefore I want to calculate the vertices in the constructor of the class (or in a seperate function..).
Although I read tons of articles about creating spheres in different ways (UV Sphere, Quad Sphere, Icosphere etc.) I did not understand how to create the vertices for my buffer object.

I decided to use the UV Sphere since it is easy to map a texture on it.

A "UV sphere" in this sense is one where the (quad) edges run like lines of latitude and longitude, and the texture is mapped to the sphere like an equirectangular projection.

(Equirectangular Earth texture by Strebe via Wikimedia Commons, CC BY-SA 3.0)

But how can I calculate all the vertex positions and texture coordinates?

For my vertices I use a Vertex struct:

struct Vertex
{
    glm::vec3 position;
    glm::vec2 texture;
};


texts:
Do 2D games still sell well? Assume it has nice visuals and good game-play.

I want to make games and want to start with 2D, but I am a bit hesitant, I have more than 8 years experience with 3D applications like Maya and other software, but not games. I'd like to know if it's worth the time investment to make 2D games.


texts: why are texture atlases called texture atlases and not image atlases

texts: More specifically, is there anything about texture atlases specific to textures? From what I've read of them, they might just as well be called image atlases. Images are not the same as textures, but textures can be created out of images.


texts: Showing Parallax entity and AutoParallax entity on same scene in AndEngine

texts:
How do I create both a parallax background and an autoparallax background in the same scene using andengine?

The problem is, I want one entity to move at a constant speed regardless of the camera's movement, and I want another entity to move depending on the camera's movement.

To do it, I created a parallax background and an autoparallax background.  The problem is, I can show these two background separately by doing mScene.setBackground(background);  But I want these two backgrounds to show at the same time.


texts:
I'm having an odd issue in my implementation of distance based object interaction in Unity. Basically it's a simple "Press [key] to [search/pickup/open/etc]" function which requires the player to be within a certain distance of the object before interaction is allowed (via mouse over).
In my scene I have 2 test objects which I have set up as similarly as possible, but they are acting differently and I cannot seem to work out why.
* http://imgur.com/a/hoAIH
* http://imgur.com/a/HbvrO
These are the setups, and the script which is on both parent objects is as follows:

public class DisplayUI : MonoBehaviour
{
    public string itemName;
    bool isSelected;
    bool isNear;

    void OnTriggerEnter(Collider col)
    {
        isNear = true;
    }

    void OnTriggerExit(Collider col)
    {
        isNear = false;
    }

    void OnMouseOver()
    {
        if (isNear)
            isSelected = true;
        else
            isSelected = false;
    }

    void OnMouseExit()
    {
        isSelected = false;
    }

    void OnGUI()
    {
        if(isSelected == true)
        {
            GUI.Label(new Rect(Screen.width / 2, Screen.height / 2, 200, 20), "Press E to search " + itemName);
        }
    }
}

For some reason the sphere/cube game object is acting as desired where the mouseover detects the edge of each mesh perfectly, and relies on the distance (within the trigger collider) too, creating the gui label as coded.
The trash can however seems to think the main trigger collider is the edge of the mesh so even when the mouse is way outside the physical mesh, the gui label is showing.
Where am I going wrong with this?


texts:
Scenario: several objects (o1, o2,.., on) have to be rendered with the z test disable, but the z values must be written to the depth buffer. In another pass, some other objects (t1, t2,..., tm) need to be rendered considering with the z test enabled, and considering the prior values from the previous pass.

Is it possible to achieve this with Unity's material script? The goal is to support a custom order for the rendering of transparent objects (the o1,..,on in the scenario description) alongside with matte objects (t1,..., tm). I tried using the features mentioned here, but the results were incorrect, i.e. as if the z values were completely discarded inbetween passes. Can anyone, perhaps, share a code stub for this scenario?


texts:
I am having a problem with turning depth to world space position.
I am using GLSL.
What could go wrong?
Here is the code:
float x = (uv.x * 2.0) - 1.0;
float y = (uv.y * 2.0) - 1.0;
float z = (depth * 2.0) - 1.0;

vec4 pos_clip = vec4(x, y, z 1.0);

vec4 inverse_pos_view = InvCamProjMatrix * pos_clip;
inverse_pos_view.xyz /= inverse_pos_view.w;

vec4 pos_ws = InvCamViewMatrix * inverse_pos_view;

return pos_ws.xyz;

Thanks.


texts: How can I draw sprites in layers based on their Y position?

texts:
I am trying to figure out the most efficient way to draw sprites in a way that they layer properly based on their Y position.

Lets say I have four objects of the same class named A, B, C, and D, and they all must be drawn. Their respective Y positions are 12, 16, 13, and 17. If I draw A then B then C then D, they will draw and lay over the tops of each other in a weird manner. I want to draw them "largest y is closest." I know you could probably use a sort routine to sort them all based on Y, but I would imagine that would generate a huge amount of lag because of all the calculations, especially when you're needing to draw about fifty or sixty objects.

What's the right way to go about drawing them? How would I modify this to include two different types of objects with similar properties (ie, "creatures" and "projectiles" ?)


texts: Pygame Updating Display Without Being Told To

texts:
The following (abridged) bit of code is inside the main loop. What I expected to happen was the entity's position to update due to velocity, then update again if it's touching a static object before drawing rects and updating the display, but when run, an entity approaching a static will always visibly intersect with the static for one frame before moving back out, like it's running ent/stc.load() (a method for drawing rects) and pygame.display.update() multiple times during each loop.

    pygame.Surface.fill(window,(100,0,0))
    for stc in statics:
        stc.load()
    for ent in entities:
        ent.vel[0]+=ent.acc[0]
        ent.pos[0]+=ent.vel[0]
        for stc in statics:
            if ent.rect.colliderect(stc):
                if ent.vel[0]>0:
                    ent.acc[0]=0
                    ent.vel[0]=0
                    ent.pos[0]=stc.rect.left-ent.box[0]
        ent.load()
    clock.tick(60)
    pygame.display.update()


texts: How to I access "Deny" message from a Lidgren client?

texts:
I'm using the Lidgren v3 network for a UDP client/server networking model. On the server end, I'm initializing a NetServer object with the NetIncomingMessage.ConnectionApproval message type enabled.

So the client is able to successfully connect and the first packet it sends is a login packet, containing a username and password supplied by the user. The server is receiving that and doing some black magic to authenticate, and everything works up to that point.

If the login fails, the server calling NetIncomingMessage.SenderConnection.Deny("Invalid Login Credentials"). I want to know how to properly receive this deny message on the client.

I'm getting the message, it shows up with a message type of NetIncomingMessage.StatusChanged. If I call ReadString on that message, I get a corrupted version of the string I passed to the Deny method on the server. The type of corruption varies, I've seen odd characters in there but in every case it's truncated and is way shorter than the string I entered.

Any ideas? The official documentation is sparse on this topic. I could use pointers from anyone who has successfully used the Lidgren library and uses the Accept or Deny methods.

Also, if I don't do any authentication and just Approve() the connection every time, stuff actually works just fine and I'm getting reliable two-way UDP traffic. (And lastly, Stack Exchange said I don't have enough reputation to use the "Lidgren" tag....???)


texts: How do I get Input Positive Button value in Runtime?

texts:
In Unity in InputManager I assigned R Button to "Restart" name.

Now that property (Restart) has another property with a key "Positive Button" and string value "R".

In the game I can show notice to user: "click R for Restart!"

But what if user will change that key in the start config window? For example   from R to T button.

Now the game should display notice: "click T for Restart!"

Question: How do I get changed Positive Button value by name "Restart" via script in Runtime? Is it possible?

p.s. in Editor I can do this:

SerializedObject inputManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]);
SerializedProperty axisArray = inputManager.FindProperty("m_Axes");

for (int i = 0; i < axisArray.arraySize; ++i) {
    var axis = axisArray.GetArrayElementAtIndex(i);
    var axisName = axis.FindPropertyRelative("m_Name").stringValue;
    if (axisName == "Restart") {
        restartButtonValue = axis.FindPropertyRelative("positiveButton").stringValue;
        break;
    }
}

But it allows to use it only in the Editor. Because it uses UnityEditor.dll


texts: Export "Lite" and "Full" versions with different package names for Google Play Console

texts:
On the Google Play Console, you can't have two games with the same package name.
Is there a way to have two of the same game with different package names, exported from the same Unity project? For example, a "lite version" with ads and a "full version" without ads.


texts: How to limit players to low-level content before they advance, if they can't die

texts:
I am making a game with the basic RPG elements: levels, xp, items, currency, stats, spells and monsters. The only different thing is that the player doesn't have hitpoints, you can't die. It's a simple game where you basically just kill and farm monsters.

Now a problem I'm facing right now is "content restriction". I don't want my players to skip the low-level monsters simply because they can't die by the high-level ones. So how can I achieve this?


texts:
I have an infinite hexagonal floor, generated by tessellating a point grid in a tessellation shader pair:

Note that this is a flat wireframe - the "shadows" are a lighting trick:

Now, I'd like to make this appear to be thick, refractive glass, but am unsure how to proceed.

The first thing that came to mind is to

set a uniform containing the requested "thickness" of the blocks
When calculating lighting, use Snell's law to calculate the optical path length a ray would take through the hex block, if it were actually as thick as the "thickness" uniform says, and sum the alpha over that length. That would give the transparency, but doesn't handle things like internal reflection / TIR, etc.

I haven't tried that yet, so I'm not sure what the visual result would be.

Ultimately, for this particular level, I'm trying to get that glass, hexagonal floor look used in Tron: Legacy during the disc battle. (See this image for an example.)

Suggestions?


texts: How to get more gentle (cloud like) noise?

texts: Recently I have started playing around with making terrain with perlin noise. Using this library  I can make A fairly fast. However, it is to squiggly to be desirable. What I want to achieve is B, where you can see more convincing slopes with the softer noise.


texts: Distance between moving, rotated rectangles in snake game

texts:
I am trying to implement basic Snake game with movement based on timestep. For now I've got something along those lines:
Update function:
glm::vec2 headPosition = glm::vec2(m_segments.begin()->m_sprite.get_position());
float angle = m_segments.begin()->m_sprite.get_angle();

m_segments.begin()->move();

for (auto it = m_segments.begin() + 1; it != m_segments.end(); it++)
{
    glm::vec2 oldPosition = it->m_sprite.get_position();
    float oldAngle = it->m_sprite.get_angle();

    it->m_sprite.set_position(headPosition);
    it->m_sprite.set_angle(angle);

    headPosition = oldPosition;
    angle = oldAngle;
}

Move function:
glm::vec2 position(m_sprite.get_position());
position.x +=  cosf(glm::radians(90.0f - m_sprite.get_angle())) * VELOCITY_SCALAR;
position.y += -sinf(glm::radians(90.0f - m_sprite.get_angle())) * VELOCITY_SCALAR;

m_sprite.set_position(position);

Basically I set next segment position to the old position of previous segment. As expected spacing between those segments is equal to timestep value. How can I calculate position so I can manipulate spacing between those segments?
EDIT
I've found following implementation of snake segments following each other:
float distance = sqrt( pow( ( snakeParts[i-1].x - snakeParts[i].x ), 2) + pow( ( snakeParts[i-1].y - snakeParts[i].y ), 2 ) );

        // Rotate to look at previous part
        snakeParts[i].r = atan2( snakeParts[i-1].y - snakeParts[i].y, snakeParts[i-1].x - snakeParts[i].x ) + ( M_PI / 2 );

        // If the distance is too far, move to the correct distance
        if( distance > FOLLOW_DISTANCE )
        {
            snakeParts[i].x += sin( snakeParts[i].r ) * ( distance - FOLLOW_DISTANCE );
            snakeParts[i].y -= cos( snakeParts[i].r ) * ( distance - FOLLOW_DISTANCE );
        }

Source (follow function): https://github.com/Grzybojad/vitaSnake/blob/master/src/player.cpp
Could somebody help me to understand what's happening here so I can apply it to my implementation?


texts: Is there a term for placeholder graphics for dialog systems?

texts:
I'm working on a game that has a lot of dialog. It has a dialog system similair to Phoenix Wright, where the characters appear onscreen when they talk, either in sprite form or as a 3d model. Usually there's mouth and eye animations as well, and their facial expressions change depending on the context of the scene.

Here's my problem: I suck at drawing. Like, massively. I enjoy writing dialog and I already have lots of dialog written down. I even made a little program for myself, which mimics how the dialog would play out in my game. Something that I don't enjoy doing, however, especially when I implement the dialog into my game, is have tags everywhere that describe the characters mood/expression instead of showing it visually. Example:

John: mostly neutral, slightly worried How was your day?
Jane: sad Not so great...

Even in the prototype stage, I would like something more... visual, to convey the scene better to everyone else and really get the right mood and expression of the character across. That way, it would be easier for the future artist to draw the necessary poses, expressions, animations, etc. for each character.

What I would like to do is have placeholders of blank (mostly featureless) characters that have lots of different expressions to convey what I want the character to look like in that situation. I'm not asking where to find something like that, I simply want to know if there is some sort of game developer jargon/term for this kind of thing (animated or still), so I can narrow down my search a little.


texts:
I would like to structure my gui into different panels.
so to help keep my code managable i thought it might be a good idea to have a main panel. with its own manager and then a secondary panel with its own manager that gets drawn ontop of the main panel.
Ideally I would have a main screen with a couple of buttons on the left. In the centre of the main screen I can show different panels. (Think of a website with a navbar on the side)
This would make it easier to work on the individual panels and also allow me to place buttons on the panels relative to the panels they will appear on as opposed to having to place them relative to the main panel.
My problem now is that I can't seem to get the events from any of the secondary managers into pygame's event queue.
Is this at all possible?
Do I need to show my not-working code?


texts: How to move around a player in a curved tunnel?

texts:
In a scenario where the player moves freely along the walls of a tunnel (like this), what is the best way to move the player along the walls of the tunnel?

I'm using Unity3d game engine. I've tried to remove all gravity and apply relative downward force on the object on every tick. Pressing right or left key applies relative force on the x-axis. But the player object will not rotate along with the walls of the tunnel and hence wont climb. I can calculate tangent to the center of the circle inside the tunnel and rotate the player myself but that wont work with curved tunnels.


texts:
My 2D camera follows the character fine without any zooming. However, when I tried adding a zoom feature using the Matrix.CreateScale(), the camera no longer follows the character properly.

public class Camera
{
    private Matrix transform;

    public Matrix Transform
    {
        get { return transform; }
        set { value = transform; }
    }

    public Viewport view;
    public  Vector2 center;
    float zoom;
    float rotation;
    public float Zoom{
        get{return zoom;}
        set { value = zoom; }
    }

    public Camera(Viewport newView)
    {
        view = newView;
        zoom = 2;
        rotation = 0;
    }

    public void Update(Vector2 position, int xOffset, int yOffset)
    {

        if (position.X < view.Width / 2)
            center.X = view.Width / 2;
        else if (position.X > xOffset - (view.Width / 2))
            center.X = xOffset - (view.Width / 2);
        else center.X = position.X;

        if (position.Y < view.Height / 2)
            center.Y = view.Height / 2;
        else if (position.Y > yOffset - (view.Height / 2))
            center.Y = yOffset - (view.Height / 2);
        else center.Y = position.Y;

        transform = Matrix.CreateTranslation(
            new Vector3(-center.X + (view.Width / 2), -center.Y + (view.Height / 2), 0)) *
            Matrix.CreateScale(Zoom, Zoom, 1.0f) * Matrix.CreateRotationZ(rotation) *
            Matrix.CreateTranslation(-center.X + (view.Width / 2), -center.Y + (view.Height / 2), 0);

    }
}

The camera is updated with:

camera.Update(character.Position, map.Width, map.Height);

With the width and height of the tilemap and the characters current position.
If I change the zoom factor how do i keep the player still in the center w/ the camera following?


texts: Procedural terrains in 3D: what has been done ? Are there common algo and/or theories about it?

texts:
Besides programming, modeling an environment takes a great deal of time.

I don't know about the work time involved, for example, in a WoW dungeon level, or other beautiful city-like, future environment, jungles, fantasy, etc, but this kind of work is made from scratch by artists.

What are the techniques involved in the TorchLight level randomizer, and does other titles have similarities with this ? Is there a family name for such techniques ?


texts: Need an ideal opensource 3D engine for building Golf simulation game

texts:
I'm looking for a open-source 3D graphics and physics engine specialized in golf simulation.

The preferred engine would be have short learning curve, supports Windows platform and Java or C++ and Lua/Python support for scripting, also prefer something like outdoor golf plane scene with weather system support, I'm new to this area and would love to hear all of your advice.

I'm just come from stackoverflow site, @mikera there recommends jMonkeyEngine, it sounds a fit, but I'm not sure if there's other ideal candidate engine?


texts: How to remove an object from a std::vector

texts:
So I have a vector of bullets that show up on the screen and I do not want these bullets to live forever. I want them to "die as soon as they go off screen or collide with an enemy. How can I make sure they are removed from the array and no longer take up memory.

code:

std::vector<Bullet> bulletArray;

for(int i=0; i<bulletArray.size(); i++)
{
    bulletArray[i].MoveBullet();
    bulletArray[i].Draw();
    if(bulletArray[i].PosY<0)
    {
        //Delete object forever
    }
}


texts:
I want to create a menu for a game using a color gradient as the background. Is there a way to create a gradient background instead of using an image for it (since I don't know what size the window will be, using an image is no option).

Please note: I need to achieve this using only the C standard library and the SDL, no other library and no C++.


texts: Convert "analog stick radians" into "normal radians / degrees"

texts:
Sorry if the title isn't self explanatory. I've worked previously on the development of many small indie games for computers, but never really bothered on developing anything for a console, until recently when I got accepted for an indie development program for a well known game console. The games I'm working on (as most console games) will use the analog sticks for moving the character and rotating the camera, so far so good... except that the analog sticks don't work as I thought they would. When the analog stick is facing up, the "value" returned is pi / 2 (90°). When it's facing to the left the value is 0. When it's facing down, the value is (-pi / 2) (-90° ??) and when it's facing on the right the value is either -pi (-180° ??) or pi (180°). And obviously there are values in between all of those.

Small "ascii art" to demonstrate what I mean.

        ^   pi /2
+- pi <   > 0
        V   -pi /2

The values that I don't get are the negative ones, how can I convert those negative values to an actual circle, so that I get a value between 0° and 360° (0 and 2 pi)?

Sorry if the question might sound stupid, I'm really new to console development. At first I thought I would ask in the official developers forum for this game console, but I thought that a public resource like stack exchange might be better since, I'm most likely, not the only one that has to deal with this, and probably other consoles have the same mechanism too.


texts:
I'm trying to replicate the movement in this game: https://www.youtube.com/watch?v=OcvD8BXars8

The players ship along with all other game elements move along the surface of a mesh.

I've tried replicating this by ray-casting down on the mesh to have an idea of the up direction which is fairly straightforward, the problem is rotating the object on the axis of that normal such that the front is always facing the way the player intended (when the player is moving on the mesh the hit normal changes throwing everything off).


texts:
Recently I've been working on a fast-paced 2d shooter and I came across a mighty problem. Collision detection. Sure, it is working, but it is very slow.
My goal is: Have lots of enemies on screen and have them to not touch each other. All of the enemies are chasing the player entity. Most of them have the same speed so sooner or later they all end up taking the same space while chasing the player. This really drops the fun factor since, for the player, it looks like you are being chased by one enemy only. To prevent them to take the same space I added a collision detection (a very basic 2D detection, the only method I know of) which is.

Enemy class update method
    Loop through all enemies (continue; if the loop points at this object)
        If enemy object intersects with this object
            Push enemy object away from this enemy object

This works fine. As long as I only have <200 enemy entities that is. When I get closer to 300-350 enemy entities my frame rate begins to drop heavily. First I thought it was bad rendering so I removed their draw call. This did not help at all so of course I realised it was the update method. The only heavy part in their update method is this each-enemy-loops-through-every-enemy part. When I get closer to 300 enemies the game does a 90000 (300x300) step itteration. My my~

I'm sure there must be another way to aproach this collision detection. Though I have no idea how. The pages I find is about how to actually do the collision between two objects or how to check collision between an object and a tile. I already know those two things.

tl;dr? How do I aproach collision detection between LOTS of entities?

Quick edit: If it is to any help, I'm using C# XNA.


texts:
I have an array of 3d vertices, Vertex3D[][] ground;
so for each element in the array, I have an array of three 3D vertices, a triangle.

But this means I cannot implement a quad tree, and I cannot render polygons far away from the player with less accuracy, this also means I cannot have caves because one point on the map can only have one height (y) value. How are 3D maps stored (as in what data structure) to allow further polygons to be larger and close ones to be smaller as well as having different levels (height) at the same (x,z) coord?


texts: Preload multiple scenes at the same time and activate them on demand in Unity. [Unity, async, simultaneous]

texts:
Preload scene in unity - this question tells us about how we can pre-load a scene in Unity and load it on demand. What it doesn't tell us - how do we pre-load multiple scenes at the same time and also keep the other scenes in memory waiting to be activated when we load another scene?
Use case: pre-loading multiple scenes at the start of the application, so they are ready when required. Example:

You have a [Scene] Intro which takes 20s to complete where you start pre-reloading [Scene] Main Menu that takes 10s to load. When [Scene] Main Menu has finished pre-loading, you still have 10s to spare, those could be used to pre-load [Scene] Main Game.
You have a [Scene] Main Menu. Depending on user choice you load [Scene] Main Game or [Scene] Sandbox. You pre-load both scenes while user is still in [Scene] Main Menu. When user makes their choice, chosen pre-loaded scene is loaded.


texts: Separating game data/logic from rendering

texts:
I'm writing a game using C++ and OpenGL 2.1.
I was thinking how could I separate the data/logic from rendering.
At the moment I use a base class 'Renderable' that gives a pure virtual method to implement drawing. But every object has so specialized code, only the object knows how to properly set shader uniforms and organize vertex array buffer data. I end up with a lot of gl* function calls all over my code.
Is there any generic way to draw the objects?


texts: How to move a 3d object in 3d coordinate space

texts:
How can I move a 3d object in a 3d coordinate space? I have a coordinate output from a text file like this:

-0.420 , -0.329 , 2.953
-0.296 , -0.314 , 3.136
-0.296 , -0.314 , 3.136
-0.296 , -0.314 , 3.136


texts: In DirectX 11, batching primitives for performance, how does this actually work?

texts:
I don't seem to be able to understand this. Microsoft says that one of the possible optimizations of for a Direct3D 11 if to batch primitives draw calls. For example in order to draw say 300 triangles calling the Draw method each time, you would instead pack and Draw them all at once.

The thing I don't get is how you would actually draw them in different locations and everything, because for example, I need one different world transformation matrix for each one. The only thing that comes to my mind is to calculate everything on the CPU and set the values for each vertex manually, however this approach doesn't seem like it would be a very good code optimization to me.

I feel like I'm missing something but I can't find the answer anywhere. The question is: how would you be able to pack things in a draw call without needing a render state change, and still get objects in different locations?

Note that I am not asking for pieces of code here, I'm primarily looking for a theorical answer to this.


texts: Adding force to a 3d object in a 2d scene

texts:
I have a 3d game object placed in a 2d scene (top-down view) in Unity. I want to add force to the object to move it in the direction it's facing. I attached a RigidBody2D component to it and when I use the AddForce() method, it's not working as I want it to i.e. it's moving on only one plane x or y but not in the facing direction.
Please help me.
Edit :- The game is my version of Asteroids. The ship is 3d and the asteroids are 2d. The scene is in 2d. I fixed the 'y' and 'z' rotation of the ship.
Now how do I add force to the ship in the direction its facing ?
The Update method -

void Update() {

    float rotationInput = Input.GetAxis ("Rotate");
    if (rotationInput != 0) {
        float rotationAmount = RotateDegreesPerSecond * Time.deltaTime;
        if (rotationInput < 0) {
            rotationAmount *= -1;
        }
        ship.transform.Rotate (Vector3.down, rotationAmount);
    }
    Vector3 currentRotation = ship.transform.eulerAngles;
    currentRotation.x *= Mathf.Deg2Rad;
    thrustDirection = new Vector3 (Mathf.Sin(currentRotation.x) * -1, Mathf.Cos(currentRotation.x), Mathf.Cos(currentRotation.x));

}

The FixedUpdate method -

void FixedUpdate()
{

    if (Input.GetAxis ("Thrust") > 0) {
        print (thrustDirection);
        ship.AddRelativeForce (ThrustForce * thrustDirection, ForceMode.Force);
    }

}

Thanks in advance.


texts: Checking for alternate keys with XNA IsKeyDown

texts:
I'm working on picking up XNA and this was a confusing point for me.

KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
{
    //Do stuff...
}

The book I'm using (Learning XNA 4.0, O'Rielly) says that this method accepts a bitwise OR series of keys, which I think should look like this...

KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Left | Keys.A))
{
    //Do stuff...
}

But I can't get it work. I also tried using !IsKeyUp(... | ...) as it said that all keys had to be down for it to be true, but had no luck with that either. Ideas? Thanks.


texts:
I've been looking everywhere for a solution on how to render/draw text for my 2D OpenTK-based game.

Been trying quite a few QuickFont ones without success (either a AccessViolation exception or text just not rendering), which is why I finally decided to ask here.

So my question is;
How do I render/draw text in OpenTK for my 2D game?

Thanks!

EDIT

I have tried the following example from QuickFont.Desktop GitHub

QFont _myFont;
QFont _myFont2;
QFontDrawing _drawing;

_myFont  = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true));
_myFont2 = new QFont("basics.qfont", new QFontBuilderConfiguration(true));
_drawing = new QFontDrawing();  //This line throws exception "Exception thrown: 'System.AccessViolationException' in QuickFont.dll"

As I get an error here, It's hard to tell if the rest is wrong or not. It's all in the link above for anyone interested.

What I am looking for is basically a complete "working" guide for the latest OpenTK build with .NET Framework 4.5.2


texts:
I have a basic game, in which the player moves the environment around the screen, to give the gamer an impression that the player is actually moving.
I want this game to be large and have an open world, each piece of scenery is an object and each frame it updates the scenery to make itself move relative to the player. The trouble is with large amounts of objects this causes the game to slow down, but the objects HAVE to be updated otherwise they will become out of synch with the player. So how can I increase the performance of my game without splitting it up into tiny little levels?

Its a 2D top down game. The position of each object is updated each time, but when there are a large number of objects this takes a long time.


texts: DirectoryNotFoundException for an existing file path (continued)

texts:
DirectoryNotFoundException for an existing file path on Unity startup
I did what TehMightyPotato suggested (see the link above), and managed to solve the issue. However, the next day when i opened up the same project, Unity was unable to find the .asmdef files. It seems like rearranging the .asmdef files deleted them as well.
What can i do to solve this problem?


texts: Can't load model using ContentTypeReader

texts:
I'm writing a game where I want to use ContentTypeReader. While loading my model like this:

terrain = Content.Load<Model>("Text/terrain");

I get following error:

Error loading "Text\terrain". Cannot find ContentTypeReader
AdventureGame.World.HeightMapInfoReader,AdventureGame,Version=1.0.0.0,Culture=neutral.

I've read that this kind of error can be caused by space's in assembly name so i've already removed them all but exception still occurs.

This is my content class:

[ContentTypeWriter]
public class HeightMapInfoWriter : ContentTypeWriter<HeightmapInfo>
{
    protected override void Write(ContentWriter output, HeightmapInfo value)
    {
        output.Write(value.getTerrainScale);
        output.Write(value.getHeight.GetLength(0));
        output.Write(value.getHeight.GetLength(1));

        foreach (float height in value.getHeight)
        {
            output.Write(height);
        }
    }

    public override string GetRuntimeType(TargetPlatform targetPlatform)
    {
        return
            "AdventureGame.World.Heightmap,AdventureGame,Version=1.0.0.0,Culture=neutral";
    }

    public override string GetRuntimeReader(TargetPlatform targetPlatform)
    {
        return
        "AdventureGame.World.HeightMapInfoReader,AdventureGame,Version=1.0.0.0,Culture=neutral";
    }
}

Does anyone meed that kind of error before?


texts: Unity : Casting shadows of anima2d characters

texts:
I want to cast shadows of animated 2d character on a level like this :

The only thing here I want is dynamic shadows for anima2d character as animation progresses.Is there a way of achieving shadows with anima2D characters?


texts: What is actually loaded during a game's loading screen?

texts:
I am at the stage of my game where I have to develop the loading screen. It's actually already there, but I don't know exactly what it should be loading while it's presented.

Why would I have a loading scene instead of just going directly to my game scene? I don't even know what else to load besides the textures with the texture SpriteCache.

Am I doing the correct content loading? I missing something to load during that loading scene?


texts: "The Game Object" - and component-based design

texts:
I've been working on some hobby projects the last 3-4 years. Just simple 2d and 3d games. But lately I have started a bigger project. Soo in the last couple of months I've been trying to design a game object class which can be the base of all my game objects. So after much try & die testing I turned to Google which quickly pointed me to some GDC PDFs and PowerPoints. And now I'm trying to get the grasp of component-based game objects.

I understand that the engine creates a game object and then attaches different components which handles things like health, physics, networking and whatever you make them do. But what I don't understand is how component X knows if Y has changed the state of the object. Like how does the PhysicsComponent know if the player is alive, because the health is controlled by the HealthComponent..? And how does the HealthComponent play the "player-died-animation"?

I was under the impression that it was something like this(In the HealthComponent):

if(Health < 0) {
   AnimationComponent.PlayAnimation("played-died-animation")
}

But then again, how does the HealthComponent know that the game object it is attached to have a AnimationComponent attached? The only solution I see here is

Have a check to see if a AnimationComponent is attached or not (Either inside the component code or on the engine side)
Have components require other components, but that seems to fight the whole component-design.
Write like, HealthWithAnimationComponent, HealthNoAnimationComponent, and soo on, which again seems to fight the whole component-design idea.


texts: How to adjust GUI to screen resolution ?

texts: I've created a GUI for my XNA game and now I'm stuck with a problem. My GUI element positions are designed for a max resolution of 1920x1080, and if I try changing it to 640x480 they disappear from the screen. What I can change to keep them there?


texts: How can multiple clients be out of sync if they use the same RNG seed?

texts:
I have been working on a client-server architecture to enable LAN play for my open source game, Aigilas. In its current state, players stay synced in all running instances of the game but enemies and particle animations are out of sync.

What I cannot understand is how players are the only entities staying synced. I run the clients in lockstep, requiring the latest input states from each client to be announced before taking a turn in the game world. When the game world is built, I seed the random number generator (RNG) with a seed determined by the server. This seed appears to affect the RNG as expected; each client has the same procedurally generated game world and players start in all clients at the appropriate locations.

Particle animations and AI are chosen based on player positions and the RNG. How is it possible for them to become out of sync when the players are always in sync?  To the best of my observations of both the game screen and the logs, players never go out of sync with respect to their positions. That leads me to believe that the RNG in C# is not acting deterministically across all clients.

The basic workflow for the game's client<->server communications are as follows:

Server starts
Client starts and gets RNG seed from server
Client tells server when keys are pressed/depressed by a user
Once a game has started, server tells all clients the current state of each player's keyboards
Once an update has been received from the server, one turn of the game is simulated
Repeat step 4

If there are any specific questions targeting a specific portion of the code, then I am happy link to the appropriate page on GitHub.


texts: Delay The Polling Events Of Xbox360 Gamepad With XInput

texts:
My team and I are currently developing a 2D platformer with SDL/OpenGL and we want to add support to the Xbox360 Gamepad with the XInput library from Microsoft, but we are currently having a problem.

First of all, the method for reading the key states it's this one:

bool InputMapping::Gamepad::checkKeyState(WORD button)
{
  DWORD dwResult;
  DWORD idPlayer = playerID - 1;

  XINPUT_STATE state;
  ZeroMemory( &state, sizeof(XINPUT_STATE) );

  dwResult = XInputGetState( idPlayer, &state );

  if ( state.Gamepad.wButtons & button)
  {
    return true;
  }

  return false;
}

This method returns true or false if the selected key it's pressed or not.

But it seems that the polling of the keys it's ocurring really fast, in the menus, moving through the buttons it's really fast and I can't controlled.

There is a way to limit the time between polling inside of the XInput or I should do it by myself? or what you recommend me?

If I didn't explain me clearly don't hesitate in say that.

Thanks a lot.


texts: How to create a grid movement like the oldschool snake game?

texts:
I got 2 problems with the game,

I don't know how make my GameObject (snake head) move based in a grid for some reason I don't know it moves freely on the screen.
The tail keep instantiating above the head not behind... I tried many things and did not work and didn't find an answer in the forum that helps me.

Now I'm back to the begin and looking if someone can help me.

This is the code I use to generate a grid. If anyone could help me with some code, I appreciate it.

public class LevelManagerTest : MonoBehaviour
{

    public GameObject tile;
    [SerializeField]
    private Transform gridParent;
    [SerializeField]
    public Transform[,] Grid;

    private GameObject[,] grid = new GameObject[12, 7];

    public float TileSize
    {
        get { return tile.GetComponent<SpriteRenderer>().sprite.bounds.size.x; }
    }

    void Start()
    {
        CreateLevel();
    }

    private void CreateLevel()
    {
         Vector3 worldStart = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height));

        for (int y = 0; y < 7; y++)
        {
            for (int x = 0; x < 12; x++)
            {
                PlaceTile(x, y, worldStart);
                grid[x, y] = tile;
            }
        }
    }

    private void PlaceTile(int x, int y, Vector3 worldStart)
    {
        // creates a new tile and makes a reference to that file in new tile variable
        GameObject newTile = Instantiate(tile, gridParent);

        //uses the new tile reference and change the position of the tile
        newTile.transform.position = new Vector3(worldStart.x + (TileSize * x), worldStart.y - (TileSize * y), 0);
    }
}


texts: How can you create a side-scrolling beat-em-up perspective in Unreal Engine?

texts:
How can I achieve Streets of Rage type of perspective in UE4? By that, I mean having a 2D character that walks "into" the screen, but the character doesn't get smaller or angled in any way.

Is there a camera setting that allows that? Or some kind of character setting?

Also, how would I set up the background? I'm pretty sure that it's just a static image that is put behind on a plane, but maybe there's a better way to do that?

I already created a game that attempted this with a friend during a game jam, but the camera view doesn't look the way we want.


texts: Unity / How do I change the color of the "Screen" based on the Object's depth's (as a Screen Effect)?

texts:
Yesterday I asked and solved my problem:

Unity / How do I change the color of an object based on its depth?

Today I tried to change the script(from yesterday) and apply it to the camera and it did not work.

Every pixel which is printed on the Display has a depth (float), is that right?

Based on that Depth - I want every object to fade grey, relative to the screen distance to that "pixel".

Is this possible?

Or do I have to use that vertex/fragment shader on every single Object and Plane and Sky and everything in the world?


texts: Help with the calculation of the usage of my speed stat

texts:
I am working on a freeroam, action RPG (before you read further, I am not noobish to programming, plus have friends to help with actual content rather than the base code). Anyway, I am trying in Skills to the game. I decided the movement-based skills and animations should be a priority, so I began integrating it in. The animations work fine, but alas my movement skill Athleticism is making the character move unrealistically fast at a higher skill. The skill ranged from 1 to 100. After realising I should do some calculations to make you go from normal to Sonic the Hedgehog, I am using this formula currently:

(Athleticism / Mathf.Sqrt(Athleticism)) * 0.05f * runMod;

This has helped, but it still looks weird. I need some help to make a formula that makes that the skill doesn't have such of a linear effect on the movement.

EDIT:

Trying to be specific. The player moves, currently about 0.05 walking units per second at Athleticism 10, which is nice. However, the movement rate at Athleticism 100 cranks up to 0.15 units, which is a little too fast. I am aiming for 0.1 instead.


texts:
I don't understand the purpose of separate SystemClass for functions.
My composition looks like this:

class Color {
   void Blend(uint32_t entityID, float factor) {
      red[entityID] *= factor;
      green[entityID] *= factor;
      blue[entityID] *= factor;
   }

   static std::vector<float> red;
   static std::vector<float> green;
   static std::vector<float> blue;
}
std::vector<float> Color::red;
std::vector<float> Color::green;
std::vector<float> Color::blue;

I am keeping vectors of members to have possibility to iterate over specific member instead of loading whole struct.

My question is: what exactly is the reason for SystemClass with only logic?

class ColorComponent {
   static std::vector<float> red;
   static std::vector<float> green;
   static std::vector<float> blue;
}
std::vector<float> ColorComponent::red;
std::vector<float> ColorComponent::green;
std::vector<float> ColorComponent::blue;

class ColorSystem {
   void Blend(uint32_t entityID, float factor) {
      ColorComponent::red[entityID] *= factor;
      ColorComponent::green[entityID] *= factor;
      ColorComponent::blue[entityID] *= factor;
   }
}

How the second composition suppose to be better for performance?

I will be very grateful for explanation.


texts: Find projecting triangle for UV mapping in RuneScape model format

texts:
I am using an old Runescape model format, also used by Thief and Quake. In this format, instead of specifying UV coordinates for each vertex ABC, we specify a second trio of vertices PMN. Those vertices are then used to project UV texture coordinates onto ABC.
Some previous Q&A explains this projection algorithm and how to reverse it.
I have a mesh with UVs that I want to save in this format. To do that, I want to find a trio of vertices PMN for each triangle ABC that reproduce the correct UVs.
These PMN vertices are chosen from the collection of vertices already in my mesh.
I could search every possible ordered triangle in my mesh, but that scales as \$O(n^3)\$ and would be impractical for meshes with high vertex counts.
How can I more efficiently find a PMN triangle that produces my desired UV coordinates on each triangle ABC?


texts: Is it possible to gain performance by omitting vertex normals in the GPU pipe?

texts:
I am working on a rendering problem where I want to render as many raw triangles to the screen as I can with either OpenGL or DirectX with the absolute fastest performance possible.

I wondered about omitting vertex normals completely and only transforming vertex positions during the vertex shader stage.

1)  Is this possible?

2)  Is it actually going to increase performance --or-- is the "bare metal" of the GPU designed in such a way that trying to omit normals won't gain any more throughput?

p.s.  Yes, I realize that omitting normals will leave you with the problem of how to shade the triangle during the shader stage, but I could at least render a solid color to the screen (no shading).  At this point, all I'm wondering about is how much data I can eliminate from the typical pipeline to increase the pipeline throughput to the absolute maximum.


texts:
I'm using a tile based collision, but when the game is lagging (the lag isn't the problem) the collision fails and the player falls through tiles.

This is the movement/collision detection code of my Player class:

gravity.y = gspeed;

speed.y+=gravity.y;

position.set(position.x + direction.x * speed.x * deltaSeconds, position.y + direction.y * speed.y * deltaSeconds);

for (int i = (int) Math.round(position.x / 32) - 2 * t; i < (int) Math.round(position.x / 32) + 3 * t; i++)
            {
                for (int j = (int) Math.round(position.y / 32); j < (int) Math.round((position.y + height + 64) / 32); j++)
                {
                    checkCollision(i, j, deltaSeconds);
                }
            }

public void checkCollision(int i, int j, float deltaSeconds)
    {
        bbox.setBounds((int) position.x, (int) position.y, (int) width, (int) height);
        Tile t = null;
        t = Map.getTile(i, j);
        if (t != null)
        {
            if (t.isSolid())
            {
                if (t.getTop().intersects(bbox))
                {
                    if (position.y + height < t.y * 32 + 32)
                    {
                        if (speed.y >= 0)
                        {
                            position.y = t.y * 32 - height;
                            speed.y = 0;
                            gravity.y = 0;
                            jumpState = 0;
                        }

                    }

                }
                if (t.getBottom().intersects(bbox))
                {
                    if (position.y < t.y * 32 + 32)
                    {
                        position.y = t.y * 32 + 32;
                        speed.y = 0;
                    }
                }
                else
                {
                    if (t.getLeft().intersects(bbox))
                    {
                        if (position.x + width > t.x * 32)
                        {
                            position.x = t.x * 32 - width;
                            speed.x = 0;
                        }
                    }
                    if (t.getRight().intersects(bbox))
                    {
                        if (position.x < t.x * 32 + 32)
                        {
                            position.x = t.x * 32 + 32;
                            speed.x = 0;
                        }
                    }
                }
            }

        }
    }

Is it possible to fix my code, if yes how? Or is it possible to tell if the game is lagging?


texts: How do I fix "Invalid character '' in input string at LitJson.Lexer.NextToken ()" when trying to use JSON from URL?

texts:
When trying to use a Json file served by a url I am getting the error

JsonException: Invalid character '' in input string

it happens when I use this method:

IEnumerator GetText()
{
   UnityWebRequest webjson = UnityWebRequest.Get("http://awebsite.com/Art_.json");

    yield return webjson.SendWebRequest();

    if (webjson.isNetworkError || webjson.isHttpError)
    {
        Debug.Log(webjson.error);
    }
    else
    {
        // The following line is giving me the error:
        // ItemDatabase_+<GetText>d__3.MoveNext () (at Assets/Version2.0/Scripts/ItemDatabase_.cs:38)
        itemData = JsonMapper.ToObject(webjson.downloadHandler.text);

        Debug.Log(itemData);

        ConstructItemDatabase();

    }
}

I have tried to use Trim()

itemData = JsonMapper.ToObject(webjson.downloadHandler.text.Trim());

But still have the same result.

I have tried what is suggested in this question/answer, but it seems to not fix the issue I have.


texts: Using a switch command in one shader vs multiple shaders

texts:
If you have multiple shaders, could you instead of switching between shaders all the time just have one shader with a switch and each case will send you along to another shader function which you require for that specific object? ( And  you would send an enumerated value through your constant buffer for that specific object)

I guess the real question is. What would take up the most performance, the switch or the switching between shaders?

Example:

BigShader(){
   switch(a){
      case 0 :
        { return transPSShader();}
      case 1:
        { return nonTransPSShader();}
ect.
}


texts: How to compute the forward, up and right vectors from a single quaternion?

texts:
Given a quaternion

float x, y, z, w;

How does one the forward, up and right vector from a single quaternion?

vec3 up;
vec3 forward;
vec3 right;

quat_get_all_axis(&quat, &up, &forward, &right);

This seems useful to accomplish things like move forward/back, strafe and jump.


texts: How do i instantiate the ball back to its original position once it got destroyed?

texts:
private void LockBallToPaddle()
{
    Vector2 paddlePos = new Vector2(Paddle.transform.position.x, Paddle.transform.position.y);
    transform.position = paddlePos + paddleToBall;   //For the ball to stick to the paddle
}

this is my coding for the ball stick to the paddle.
do i just instantiate as per normal? like instantiate("gameobject", transform.position) ?


texts: UE4 How to Avoid Boundary Seams with Multiple Refractive Meshes

texts:
We use multiple box meshes to create our game world in Unreal Engine 4, but we also use those boxes with translucent/sss materials with refraction. The problem is there are seams between those boxes but want to combine those meshes to make them behave like one big mesh while rendering. We don't want to leave our boxed layout.

Those boxes use all exactly the same material by the way.

Thank you for your help.


texts: What are some of the tricks engine can use to render object that have extremely high polygons efficiently? I know one thing we do is render only the parts that the camera points at, but I am wondering if there are many more techniques used other than that one.


texts: Python:Adding enemies and weapons in game (Text-based adventure game)

texts:
I'm a beginner in coding and game-design also and try to make text-based adventure game, where player should move between rooms, fight with zombies and pick up weapons. Any help, namely tips and pieces of advise regarding the direction are really appreciated.

How can I add more zombies in the game except those which are in room?

For now code is organized as follows:

def position():
# player's position
    print("You are in  : " + rooms[currentRoom]["name"])
# inventory
    print("Inventory" + str(inventory))
# weapon
  if "weapon" in rooms[currentRoom]:
      print("Pick up " + rooms[currentRoom]["weapon"])

inventory=[]

#dataset
rooms = {
    1 : {"name" : "entrance",
         "info":"Start of the game",
         'N': 2 ,
         'E': 3 ,
         'S': 'no such directory' ,
         'W': 'no such direction' },
    2:  {"name" : 'kitchen',
         "info" :'Here is a zombie! Use frying pan to fight against him',
         'N': 'no such directtory',
         'E': 4 ,
         'S': 1 ,
         'W': 5 ,
         "weapon" : "frying pan"},
    3 : {"name":'livingroom',
         "info":'Here is another zombie who likes to play golf. Give him
         golf clubs and run',
         'N': 4 ,
         'E' :'no such directory',
         'S': 'no such directory',
         'W': 1,
         "weapon" : "golf clubs"}
    ...
        }
currentRoom = 1

displayIntro()

while True:

    position()

    moving = input (">>").lower().split()

    if moving[0] == "go":
        if moving[1] in rooms[currentRoom]:
            currentRoom = rooms[currentRoom][moving[1]]
        else:
            print("There is no such direction")

    if moving[0] == 'get':
        if "weapon" in rooms[currentRoom] and moving[1] in
            rooms[currentRoom]["weapon"]:
            inventory += [moving[1]]
            print(moving[1] + "got!")
            del rooms[currentRoom]["weapon"]
        else:
            print("can't pick up " + moving[1] + "!")

By running the code, only first word of weapons is added to inventory. Can you please explain what is a reason?


texts:
I'm trying to rotate a ship in an asteroid game. What I'm doing is creating a float angle variable and at each time I press left or right buttons, I increase and decrease it, and in the drawing function, I rotate the ship by that amount.

The behaviour that I get is not really correct, because what I want is at each press, the ship should move smoothly and not by small increments.
This is what I'm doing:

 static float ang = 20.0f;

 if(event.getCode() == KeyEvent::KEY_RIGHT)
 {
      ship.m_Angle+=ang*getElapsedSeconds();
 }
 else if(event.getCode() == KeyEvent::KEY_LEFT)
 {
      ship.m_Angle-=ang*getElapsedSeconds();
 }

 gl::pushMatrices();
 gl::translate(Vec2f(m_Pos.x,m_Pos.y));

 gl::rotate(Vec3f(0,0,m_Angle));
 gl::scale(0.3,0.3,0.3);
 gl::color(ci::Color(1,1,1));

 gl::drawLine(Vec2f(-52,-23),Vec2f(69,0));
 gl::drawLine(Vec2f(-43,-20),Vec2f(-43,20));
 gl::drawLine(Vec2f(69,0),Vec2f(-52,23));
 gl::popMatrices();

EDIT: I would also like to limit the angle, it goes forever and the variable will overflow.


texts:
I am following this video tutorial on how to implement drag-to-select behavior like in an RTS. The only difference is, I'm using a tilemap.
The selection area is a square which I can drag to make it as big as I want, like in any top down RTS.
CodeMonkey in his video uses Physics2D.OverlapAreaAll to get a list of all colliders in the selected area. I want to use this to specifically see which "vegetation" tiles I've selected. However, no matter which vegetation tile I select, or how many, I always get one result - the vegetation tilemap itself.
You can clearly see from this picture that every grass tile and every tree tile have a collider around them, which is why this works, but how can I get exactly those that I selected?

Other than vegetation from the tilemap, I also want this to work with GameObjects that have Box2DColliders on them, and that works out of the box. I also made those MonoBehaviors inherit an interface called ISelectable, so I can only add to the selected list entities that have that inherit that interface. I tried to do the same with vegetation like so public class Vegetation : Tile, ISelectable but it doesn't work.
What am I missing? Can this even work on a specific tile basis?


texts: Optimization of 2D terrain generation algorithm

texts:
I am generating 2D terrain with 2D opensimplex noise, however I am having a problem with the FPS that is low when generating the terrains in TileMap. An example of how my game generates the terrain in javascript:

function generator(map_size=0, _posWorld=[0, 0], size=[1, 48], seed=0) {
    var simplex = new SimplexNoise(seed);

    var x = 0;
    var y = 0;
    var pos_modx = 0;
    var pos_mody = 0;
    while (x < size[0]) {
        pos_modx = utilsfunctions.mod(_posWorld[0] + x, map_size);
        y = 0
        while (y < size[1]){
            pos_mody = utilsfunctions.mod(_posWorld[1] + y, map_size);
            // GENERATION NOISE
            // TEMPERATURE
            var nx = parseFloat(pos_modx)/map_size - 0.5;
            var ny = parseFloat(pos_mody)/map_size - 0.5;
            var v1 = temperature * simplex.noise2D(1 * nx, 1 * ny);
            var v2 = 0.4 * simplex.noise2D(2 * nx, 2 * ny);
            var v3 = 0.23 * simplex.noise2D(4 * nx, 2 * ny);
            var v4 = 0.134 * simplex.noise2D(8 * nx, 8 * ny);
            var e = v1 + v2 + v3 + v4;

            // HUMIDITY
            var unx = parseFloat(pos_modx)/map_size - 0.4;
            var uny = parseFloat(pos_mody)/map_size - 0.5;
            var u1 = humidity * simplex.noise2D(1 * unx, 1 * uny);
            var u2 = 0.6 * simplex.noise2D(2 * unx, 2 * uny);
            var u3 = 0.7 * simplex.noise2D(4 * unx, 2 * uny);
            var u4 = 0.073 * simplex.noise2D(8 * unx, 8 * uny);
            var u5 = 0.09 * simplex.noise2D(16 * unx, 16 * uny);
            var u6 = 0.03 * simplex.noise2D(32 * unx, 32 * uny);
            var ue = u1 + u2 + u3 + u4 + u5 + u6;

            if (pos_modx >= 0 && pos_mody >= 0) && (pos_modx < map_size && pos_mody < map_size) {
                tile_map.set_cell(_posTileMap.x + x, _posTileMap.y + y, biomes.solos(e, ue));
            }
            y += 1;
        }
        x += 1;
    }

The problem is that I am generating several layers of tilemap, one for terrain, one for relief and one for trees. That is three scripts of these, of course for the relief and trees is much less complex, and alone for example, even the two together do not interfere almost anything in the FPS. However, only generating with the above-ground script is already a big problem, and I generate only one minimum possible bit at a time, which is (1, 48) for when moving up or down, and (48, 1) when moving to the right and left, it is clear that there is the case of the diagonal movement, having to generate 48 + 48, which is the worst case. However, even only the 48 are already leaving the FPS bad, nor do I need to move diagonally to feel the FPS suffer.

I would like tips to be able to optimize this generation, and if know any way to use only one algorithm to generate everything (terrain + relief + trees), or any help that can take me to a better way.

Understand why I am generating with 3 different scripts for terrain, relief and trees:

Terrains are large areas within large areas.

Reliefs are crooked lines on the map.

Trees are only points of a dirty noise on the map.


texts:
It's showing minutes seconds milliseconds but I want to show also the hours.

At the top:

private int seconds; // Seconds.
private int minutes; // Minutes.
private int hours;   // Hours.

In Update:

void Update()
{
if (seconds < 1)
        {
            seconds = 59;
            minutes--;
        }
        if (minutes < 1)
        {
            minutes = 59;
            hours--;
        }
        if (hours < 1)
        {
            hours = 59;
        }
        seconds--;

        EditorGUILayout.LabelField("Next: ", hours.ToString() + ":" + minutes.ToString() + ":" + seconds.ToString());

Update, This is what I tried:

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

public class Timer : EditorWindow
{

    private static Timer editor;
    private static int width = 300;
    private static int height = 110;
    private static int x = 0;
    private static int y = 0;
    int totalSeconds;

    [MenuItem("Window/Timer")]
    static void ShowEditor()
    {
        editor = EditorWindow.GetWindow<Timer>();
        editor.Init();
    }

    public void Init()
    {
        StartTimer(1, 1, 50);
        Debug.Log("The level will now be saved automatically");
    }

    void OnGUI()
    {
        EditorGUILayout.LabelField("Next: ", TimeString());
    }

    public void StartTimer(int hours, int minutes, int seconds)
    {
        totalSeconds = seconds + 60 * minutes + 60 * 60 * hours;
    }

    string TimeString()
    {
        return string.Format("{0:00}:{1:00}:{2:00}",
                      totalSeconds / (60 * 60),   // Hours
                      (totalSeconds / 60) % 60, // Minutes
                      totalSeconds % 60);     // Seconds
    }
}

But the timer is not moving not counting back it stay still.
I tried also to move the line:

StartTimer(1, 1, 50);

To be inside the OnGUI before the LabelField.


texts: How do I control texture appearance based on game play events?

texts:
In an FPS I am developing, I am procedurally altering the appearance of textures based on game play events, and would like to know if the way I have implemented this was a good idea.

Right now, on each frame, I am grabbing a pointer to the uncompressed image and writing to it using memset. It's pretty straightforward if I want to have game play events affect the texture's appearance, because all I have to do is tie whatever attribute I like from any game object into the function writing the image data. For example, using this I could get the player's x,y position and draw an x directly to a map texture as the player moves around.

Is there a better way to implement this functionality in general?

My first thought would be to use shaders instead, but I haven't been able to find anyone doing anything like this and I know almost nothing about shaders. I feel like I could be missing something obvious to someone.

I am trying to keep this question as engine-independent as possible, but if relevant, I am using Source Engine procedural materials.


texts:
I created a FpsCounter DrawableGameComponent (linked to code, it's longish). It works great: It displays 60.0 fps normally. If I artificially slow down the game loop, it drops.

My 'game' at the moment is a single keyboard-controlled sprite, so it should be possible to render more frequently than 60 frames a second.

I figured turning off vertical synchronization would increase the FPS cap:

public Game1()
{
    _graphics = new GraphicsDeviceManager(this)
                    {
                        PreferredBackBufferWidth = WindowWidth,
                        PreferredBackBufferHeight = WindowHeight,
                        SynchronizeWithVerticalRetrace = false,
                    };
    _graphics.ApplyChanges();
    Content.RootDirectory = "Content";
}

However, even though the above code seems like it should turn off vsync, it doesn't seem to be. Is there something wrong with my constructor, or perhaps my FPS calculations? Or is there something else that may be limiting the frame count?


texts: Is it legally possible to make a clone of the game?

texts: With board games like "Monopoly", "Domino", "Checkers", or "Chess", can game developers make clones and sell them? Also, can I make a clone of ZX Spectrum games? Are there many parts of the game with which can do the same?


texts: What should I do to prevent my monsters from walking off platforms?

texts:
I have a question that is driving me crazy because I think it should be fairly easy to find a tutorial on it. I'm currently using XNA and Farseer to create a simple platformer game. I'm about to be done with it but I want my monsters to be smarter. In this case that means that I don't want my monsters to fall off cliffs.

To put it simply, I want something that checks the area in front of my "monster" in order to determine when the monster should change direction. Could you guys point me in the right direction?

What am I supposed to use, there should exist a simple solution or simple algorithm to check this, no?


texts: Semi Fixed-timestep ported to javascript

texts:
In Gaffer's "Fix Your Timestep!" article, the author explains how to free your physics' loop from the paint one.

Here is the final code, written in C:

double t = 0.0;
const double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
     double newTime = time();
     double frameTime = newTime - currentTime;
     if ( frameTime > 0.25 )
          frameTime = 0.25;   // note: max frame time to avoid spiral of death
     currentTime = newTime;

     accumulator += frameTime;

     while ( accumulator >= dt )
     {
          previousState = currentState;
          integrate( currentState, t, dt );
          t += dt;
          accumulator -= dt;
     }

     const double alpha = accumulator / dt;

     State state = currentState*alpha + previousState * ( 1.0 - alpha );

     render( state );
}

I'm trying to implement this in JavaScript but I'm quite confused about the second while loop...

Here is what I have for now (simplified):

...
(function animLoop(){
  ...

  while (accumulator >= dt) { // While? In a requestAnimation loop? Maybe if?
    ...
  }

  ...
  // render

  requestAnimationFrame(animLoop); // stand for the 1st while loop [OK]
}())

As you can see, I'm not sure about the while loop inside the requestAnimation one...

I thought replacing it with a if but I'm not sure it will be equivalent...

Maybe some can help me.


texts:
I'm having issues with the depth components of my shadowmapping shaders.
The shadow map rendering shader is fine, and works very well.
The world rendering shader is more problematic.
The only value which seems to definitely be off is the pixel's position from the light's perspective, which I pass in parallel to the position.

struct Pixel {
    float4 position : SV_Position;
    float4 light_pos : TEXCOORD2;
    float3 normal : NORMAL;
    float2 texcoord : TEXCOORD;
};

The reason that I used the semantic 'TEXCOORD2' on the light's pixel position is because I believe that the problem lies with Direct3D's interpolation of values between shaders, and I started trying random semantics and also forcing linear and noperspective interpolations.

In the world rendering shader, I observed in the pixel shader that the Z value of light_pos was always extremely close to, but less than the W value.
This resulted in a depth result of 0.999 or similar for every pixel.

Here is the vertex shader code :

struct Vertex {
    float3 position : POSITION;
    float3 normal : NORMAL;
    float2 texcoord : TEXCOORD;
};

struct Pixel {
    float4 position : SV_Position;
    float4 light_pos : TEXCOORD2;
    float3 normal : NORMAL;
    float2 texcoord : TEXCOORD;
};

cbuffer Camera : register (b0) {
    matrix world;
    matrix view;
    matrix projection;
};

cbuffer Light : register (b1) {
    matrix light_world;
    matrix light_view;
    matrix light_projection;
};

Pixel RenderVertexShader(Vertex input) {

    Pixel output;

    output.position = mul(float4(input.position, 1.0f), world);
    output.position = mul(output.position, view);
    output.position = mul(output.position, projection);

    output.world_pos = mul(float4(input.position, 1.0f), world);
    output.world_pos = mul(output.world_pos, light_view);
    output.world_pos = mul(output.world_pos, light_projection);

    output.texcoord = input.texcoord;
    output.normal = input.normal;

    return output;
}

I suspect interpolation to be the culprit, as I used the camera matrices in place of the light matrices in the vertex shader, and had the same problem.
The problem is evident as both of the same vectors were passed to a pixel from the VS, but only one of them showed a change in the PS.

I have already thoroughly debugged the matrices' validity, the cbuffers' validity, and the multiplicative validity.
I'm very stumped and have been trying to solve this for quite some time.

Misc info :
The light projection matrix and the camera projection matrix are the same, generated from D3DXMatrixPerspectiveFovLH(), with an FOV of 60.0f * 3.141f / 180.0f, a near clipping plane of 0.1f, and a far clipping plane of 1000.0f.

Any ideas on what is happening?


texts: How to execute a piece of code for X seconds in Andengine?

texts:
I need to execute some code in my game for 5 seconds using the Andengine framework. So far, I've tried with the onTimePassed update handler:

 scene.registerUpdateHandler(new TimerHandler(5f, true,new ITimerCallback() {

            public void onTimePassed(final TimerHandler pTimerHandler) {
                                    // code here
                }

But that only executes AFTER 5 seconds have passed by. I've also tried with the onUpdate but, keeping apart performance issues, there's no way I can count how many seconds have passed by since the execution entered the loop. If it helps, I only need the code to execute once per second for 5 seconds.
Thank you!


texts: I have a transformed Matrix A and an another transformed Matrix B. How can I COPY the rotation of Matrix B to Matrix A?


texts: Spawn prefabs from list one by one when trigger is touched

texts:
I am trying to spawn one gameobject from a list of gameobjects each time I touch the trigger with the controller.

But when I do this, all the game objects from the list spawn together at the same time. I couldn't figure out how to solve this problem and make them spawn one at a time instead, where the next touch spawns the next object in the list, and so on.

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

public class Trigger : MonoBehaviour
{

    public Transform spawnPoint;
    //public GameObject Prefab;
    public List<GameObject> items = new List<GameObject>();

    void OnTriggerEnter(Collider other)
    {
        //GameObject Prefab = new GameObject("prefab");

        for (int i = 0; i < items.Count; i++)
        {
            Instantiate(items[i], spawnPoint.position, spawnPoint.rotation);
            Debug.Log("Hello World" +i);
        }

    }

}


texts: Doing powerups in a component-based system

texts:
I'm just starting really getting my head around component based design.  I don't know what the "right" way to do this is.
Here's the scenario.  The player can equip a shield.  The the shield is drawn as bubble around the player, it has a separate collision shape, and reduces the damage the player receives from area effects.
How is such a shield architected in a component based game?
Where I get confused is that the shield obviously has three components associated with it.

Damage reduction / filtering
A sprite
A collider.

To make it worse different shield variations could have even more behaviors, all of which could be components:

boost player maximum health
health regen
projectile deflection
etc

Am I overthinking this?  Should the shield just be a super component?
I really think this is wrong answer.  So if you think this is the way to go please explain.

Should the shield be its own entity that tracks the location of the player?
That might make it hard to implement the damage filtering.  It also kinda blurs the lines between attached components and entities.

Should the shield be a component that houses other components?
I've never seen or heard of anything like this, but maybe it's common and I'm just not deep enough yet.

Should the shield just be a set of components that get added to the player?
Possibly with an extra component to manage the others, e.g. so they can all be removed as a group.  (accidentally leave behind the damage reduction component, now that would be fun).

Something else that's obvious to someone with more component experience?


texts:
Here is my attemps to pass array to uniform array:

struct Vector{ float x,y,z; }

float threshold[2] = { 0.5, 0.25 };
Vector *kernel = new Vector[_kernel_size]; // _kernel_size==16
// fill kernel

glUniform1fv(glGetUniformLocation(_program, "t"), 2, threshold);
glUniform3fv(glGetUniformLocation(_program, "kernel"), _kernel_size, (const GLfloat*)kernel); // because Vector contains only 3 float fields this kind of casting should be ok

shader:

uniform float t[2];
uniform vec3 kernel[16];

And the results are weird. Only first float or first vector are filled with proper values. For example:

t = {0.5, 7.1830559e-042}

Even when I try change only one value (name = "t[1]") it doesn't work. I checked this on AMD CodeXL.

My graphics card is Radeon HD 5770 and I have the newest drivers. I'm using OpenGL 3.3 and GLSL 330.

What am I doing wrong?


texts: How can I make cars drive navigate an intersection without colliding?

texts:
I'm trying to create a 2D game with a traffic intersection:

My car game-objects need to pass through the intersection without colliding with each other, and without stopping, if possible.

How can I implement such a behaviour?


texts:
I have a set of boxes which create a sort of path, they don't intersect very smoothy and to help that process I'm trying ot find a way to get an angle between them that can make it easier to generate another box between the intersection points.

Here's a pic of what I mean, the crudely drawn yellow arrows are basiclaly the angles I'm trying to find to put boxes there:


texts: Are there .NET bindings for Autodesk's FBX SDK?

texts:
I'm writing a tool in C# that needs to open FBX files (and the XNA content pipeline isn't a suitable solution). I note that Autodesk only provides it's FBX SDK as a C++ class library.

Before I write it myself I thought I'd ask if anyone knows of existing .NET bindings for this SDK?


texts:
I'm working on a racing game which will have a top view from the back camera. The image below displays a similar example. I am confused about how to achieve the movement of the road if parallax scrolling is used. The road gets narrow as we move forward whereas it is broader closer to the camera. Should I focus on parallax scrolling to achieve this or is there some other technique to work with such games?

p.s. I'm using cocos2d-x as the gaming engine.


texts:
When I create a new LibGDX project the main class of Core project extends ApplicationAdapter.
Here is how it looks like.

package com.marimba.apptest;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;

public class AppMain extends ApplicationAdapter {
    @Override
    public void create () {

    }

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

    }
}

So I have to change the ApplicationAdapter to Game if I want to call setScreen method in order to switch between Screens. So what is the use of ApplicationAdapter ? When shall I use it ?


texts: Hiding text/choosing which text to show in unity

texts:
i'm making a dialogue system that reads from a text file with a portrait that changes expressions depending on the context. I'm thinking of putting in a "cue" in the text file to determine which expression to show on the screen. Like #1 for default expressions, 2 for happy, etc. But the problem is the cues will show up on the dialogue box as well.
So, is there a specific code to hide texts specifically in unity like how "\n" is not shown in other languages?
Because my other solution to this is making two separate files and scripts for the dialogue and expression cues which will probably add confusion and more problems in the future.


texts:
I'm using requestAnimationFrame to handle my frame rate in a WebGL game, and running through the Chrome profile shows that a solid 10% of the time is spent in (idle).  Why is that?  How can I reduce this time, that, unless I'm misunderstanding, is just wasted?

I'm using raw WebGL. Here's part of my rendering code:

Animator.prototype.tick = function() {
  window.requestAnimationFrame(util.bind(this.tick, this));
  if (this.paused) return;
  this.advanceWorld();
  this.drawScene();
};

Full code at: https://github.com/nickgeorge/quantum/blob/master/animator.js