texts: How to draw different textures on my cubes DrawUserIndexPrimitive with XNA?

texts:
I'm having some problem to draw textures with class "DrawUserIndexPrimitive" on Xna.

I can draw my cubes / models without problem. But I want to draw different textures on my cubes.
I loop on each "ID" of a different texture applied to my different cube. But it does not work. I apply every time buffer and vertexPosition with IndexBuffer different from my class "GraphicData."

the final texture to be applied is the same on all my cubes

thank you

Here is my code for function "Draw"

public void drawWorld(GameTime gameTime)
    {
        if (needToDraw)
        {
            int index = 0;
            foreach (GraphicData data in graphicData)
            {

                effet.LightingEnabled = false;
                effet.VertexColorEnabled = false;
                effet.TextureEnabled = true;
                effet.FogEnabled = false;
                effet.FogStart = arcadia.camera.NearPlane;
                effet.FogEnd = arcadia.camera.FarPlane;
                effet.FogColor = new Vector3(1, 1, 1);
                effet.View = arcadia.camera.View;
                effet.Projection = arcadia.camera.Projection;

                if (index == 0)
                {
                    effet.Texture = Game.Content.Load<Texture2D>("Models\\Ground\\Land\\ground_land_text1");
                }
                else
                {
                    effet.Texture = Game.Content.Load<Texture2D>("Models\\Ground\\Land\\ground_land_text2");
                }
                foreach (EffectPass pass in effet.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    //Initialize et envoie à la carte graphique le buffer et les vertices
                    if (data.vertexBuffer != null && data.indexBuffer != null)
                    {
                        Game.GraphicsDevice.SetVertexBuffer(data.vertexBuffer);
                        Game.GraphicsDevice.Indices = data.indexBuffer;
                        Game.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, data.vertexPosition, 0, data.vertexPosition.Length, data.indices, 0, data.indices.Length / 3);
                    }

                }
                index++;
            }
        }

    }


texts: Volume preserving procedural mesh deformation

texts:
I'm having difficulties trying to create a procedural mesh that deforms on impact. The deformation is meant to look and feel like metal when it is being forged. Since this is less of an aesthetic feature and more of something that would affect gameplay directly, it needs to be somewhat accurate. This means that volume of the mesh should be preserved (at least visually) such that the mesh does not gradually get too much smaller.

What I have tried:

1) Applying force on every vertex, based on the force and distance from impact point

foreach (Vector3 vertexPos in vertexList)
{
    vertexPos += (force / distanceToImpactPoint.sqrMagnitude) * impactDir;
}

This led to the entire mesh gradually becoming smaller (as mentioned earlier)

2) Take into account the dot product between the impact direction and vertex normal for each vertex, as well as lerp between impact direction and normal (to simulate sides of objects bulging out when compressed

foreach (Vector3 vertexPos in vertexList)
{
    float attenuatedForce = (force / distanceToImpactPoint.sqrMagnitude);
    float nDotD = Vector3.Dot(impactDir, currVertexNormal);
    vertexPos = attenuatedForce * nDotD * Vector3.Lerp(impactDir, currVertexNormal, nDotD);
}

This led to mesh completely splitting apart for anything that has hard shading (as there  are duplicate vertices where the edges are, and also artifacts on smooth shaded objects.

Hard Shading:

Soft Shading (sort of works, but lots of artefacts and not volume preserving)

Also, both methods break completely if force is applied to an edge.

Does anyone know of a more elegant solution to do this?


texts:
In an XNA 2D game, I am thinking about blurring the background slightly to increase the feeling of depth? I am already using parallax scrolling which works pretty well in terms of enhancing depth perception. However, some newer games e.g. Super Mario Bros. 2 on the Nintento 3DS additionally use a blurred background.

Admittedly, this is a pretty extreme example:

SMB2 on 3DS example http://www.zavvi.com/blog/wp-content/uploads/2012/08/MARIO2-580x347.jpg

For me, the blurring visually is not very pleasing but nevertheless somewhat enhances the feeling of depth. I was wondering if there are any studies or personal experiences out there on the subject?

At the moment, the blurring is created by a HLSL pixel-shader (or GLSL though Mojoshader with MonoGame) which is parameterized by the velocity of movement (the faster the more blurred).


texts:
I have this (pseudo) code:

unsigned int TextureLoc = glGetUniformLocation(programID, "objectTexture");
for(int i = 0; i < object->texturesCount; i++)
{
    glActivateTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, object->textures[i]->textureID);
    glUniform1i(TextureLoc, 0);
}

And Fragment Shader code:

in vec2 UV;
out vec3 color;
uniform sampler2D objectTexture;
void main()
{
    color = texture2D(objectTexture, UV).rgb;
}

My example is that of a house model that composes a single object, but the house walls are of Texture#1 and the roof is of Texture#2.

At first I coded that each object had it's own material/textures, but then I noticed it's a waste of memory if I'm using the same texture in multiple places, so now I have a list of objects and a list of textures.
An object can have n textures.

1. How can I get a "new" in GLSL for dynamic textures count? Some objects might have 1, some might have 10, etc... How can I control that?

2.  I have an array specifying which textureID each triangle in the object uses, but how can I use this information to properly draw the object? I send the array in the glEnableVertexAttribArray(int) function, but how can I know which texture I'm supposed to use when I'm in the shader code?

Another option I thought of was to divide all objects into smaller objects if they don't have the same texture, but I'm not sure what's the best approach to this.


texts: Primitives LINESTRIP Closing to the first point?

texts:
I'm doing a exercise form the Frank Luna book. It ask to draw a LineStrip that looks like the red line in the picture.
I'm using

 md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);

I'm getting the line that is yellow,blue and black and it is looping.
How can I make it look like the red line?

My vertex that has the points:

 Vertex vertices[] =
{
    { XMFLOAT3(-5.0f, 2.0f, 0.0f) },
    { XMFLOAT3(-4.0f, -2.0f, 0.0f)    },
    { XMFLOAT3(-3.0f, 2.0f,0.0f)      },
    { XMFLOAT3(-2.0f, -2.0f, 0.0f)  },
    { XMFLOAT3(-1.0f, 2.0f, 0.0f) },
    { XMFLOAT3(0.0f, -2.0f, 0.0f)  }

};
 My indices code is:

UINT indices[] = {

    0,1,2,3,4,5


texts: How do I initialise levels sequentially?

texts:
I have been learning opengl and I have made good progress over past few months.  However I still struggle to understand game logic in C++, I am new to C++ too.
Say I have this program.
#include <headers>

int main()
{
    #Step 1
    VAO_VBO_EBO_inits();

    while(!glfwWindowShouldClose(window))
    {
        glClearColor(.2f, .2f, .3f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT);

        #Step 2
        DrawCalss();

        glfwPollEvents();
        glfwSwapBuffers(window);
    };
    return 0;
};

For OpenGL programmers this should be clear.
With this structure, I have to load all levels and then draw part of them like so.
Step 1 feeds the gpu the vertex data and its attributes.
Step 2 binds shader programs and draws the vertices
Say I have A, B, C, D levels, within  VAO_VBO_EBO_inits(); function I have to load all A, B, C, D levels then within DrawCalss(); function will draw only related levels.
DrawCalss(); function is dynamic but  VAO_VBO_EBO_inits(); invoked only once.
What I want to do is create separate game loops for each levels and be able to switch between levels, and as I switch levels preceding level should be unloaded and next level reloaded.
Since I am new to C++ I don't know what way would be the most efficient, that's why I have not tried anything.
How do I achieve it? what is the best practice for such scenarios?


texts:
Situation:

I am working on an Entity-Component system, and I am using LuaBridge as a Lua binder.
There is only one Lua State.
Currently when I update the game objects, I just check whether it has a script defined or not. If there is, I call luaL_dostring() on it, and I call its update() function.
I have a script, where I declare a global variable in its start() (it is called when the script runs for the first time), and increment it at every update() then print it out

Question:

I would like to achieve separated inner state saving for my scripts.

For example If I add the same script to two different game objects, currently the printed out numbers will be 1,2,3,4,5,6 instead of 1,1,2,2,3,3, etc.
This is because they use the same Lua State (correct me if I am wrong)
But as I heard it's not a good practice to have a lua state for every script because If I just have 5 scripts, and I add these to 3 different game objects, there would be already 15 lua states.

How should I achieve my goal?


texts: How to create a curve from a set of points that passes through said points?

texts:
What is the best way to create a smooth curve path from a set of points? For example:

I've seen Bezier curves before, but those try to smooth out the path from the set of points, like this:


texts: What is the name of this power or value-oriented gameplay mechanic?

texts:
I would like to identify the name of a certain gameplay mechanism. It is fairly commonly seen but probably best illustrated with card games:

A game played with a pack of cards usually has card values ordered in the following way:

A > K > Q > J > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2

Sometimes the lowest-ranked card (in this case 2) is specially ruled to trump the highest-ranked card (in this case A). Is there a proper name for such a mechanism?


texts:
I created a hollow box, in Blender, and imported it into Unity. The problem is, when the game starts in Unity, and gravity is applied, the box falls apart. So there needs to be some kind of glue that holds the edges of the box together.

What Blender or Unity features do I need to apply to the box to make it a single, rigid unit, like all the edges are nailed together?


texts: Is it possible for me as an developer/owner of my paid app (released on the Google Play market) to unlock its full version for specific user?


texts: Why would you want multiple render targets?

texts: In d3d11, you can bind multiple render targets ID3D11DeviceContext::OMSetRenderTargets.  But why would you want to do this?


texts: Will an XNA "XBox 360 Project" also work on Windows?

texts:
I understand that an XNA project for XBox 360 will use a specialized version of the .NET Compact Framework.  But let's say I want to release for both XBox 360 and Windows.

Will the XBox version (using compact framework) still work if distributed for Windows, or would I need to rebuild against the regular framework (or the non-Xbox CF) in order to distribute?


texts: How to create a 2d procedural spline based road with 2 edge colliders?

texts:
I am trying to make a top down 2d spline-based road that is procedurally generated and endless. The aim is that the player starts inside the road and has to navigate the road and if he touches any of its edges he "dies" and the game reloads. I have looked at various resources online for help but can't seem to find the answer. I have tried using the Path creator tool (by sebastian lague) and followed his YouTube series and I have even tried to use Unity's 2d sprite shape asset. The issue is, with the Path creator tool, I am able to create the road procedurally, but I can't figure out how to add multiple edge colliders on its boundaries. The same issue is there for Unity's sprite shape asset except with that, I don't know how to generate the road also (procedurally) and I can't find any tutorial or resource that explains how to do so.
Can someone explain an easy way to achieve this (also, it has to be procedurally since my goal is to make it endless)?


texts: Java: refresh KeyInput to avoid sticky fingers during gameover state

texts:
In short, I am trying to avoid my keys from sticking when its in the gameover state. The problem is if the player is holding down the right button for instance and dies, then he restarts the game moving right indefinitely until the player presses down the right button again. How can I prevent this from occuring? I tried setting up a boolean variable that detects if it's pressed or not but that isn't working.

else if(state == STATE.GAMEOVER)
    {
        gameover.tick();
        MouseInput.pressed = true;
        KeyInput.pressed = false;
    }

public void keyPressed(KeyEvent e)
{
    int key = e.getKeyCode();

    for (int i = 0; i < handler.object.size(); i++)
    {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player && pressed == true)
        {
            if (key == KeyEvent.VK_W) handler.setUp(true);
            if (key == KeyEvent.VK_S) handler.setDown(true);
            if (key == KeyEvent.VK_A) handler.setLeft(true);
            if (key == KeyEvent.VK_D) handler.setRight(true);
        }
        if (key == KeyEvent.VK_ESCAPE && pressed == true)
        {
            Game.setState(Game.STATE.PAUSE);
        }
    }
}
public void keyReleased(KeyEvent e)
{
    int key = e.getKeyCode();

    for (int i = 0; i < handler.object.size(); i++)
    {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player && pressed == true)
        {
            if (key == KeyEvent.VK_W) handler.setUp(false);
            if (key == KeyEvent.VK_S) handler.setDown(false);
            if (key == KeyEvent.VK_A) handler.setLeft(false);
            if (key == KeyEvent.VK_D) handler.setRight(false);
        }
    }
}
public static boolean isPressed()
{
    return pressed;
}
public static void setPressed(boolean pressed)
{
    KeyInput.pressed = pressed;
}

    if(handler.isUp() && KeyInput.pressed == true) velY = -5;
    else if(!handler.isDown() && KeyInput.pressed == true) velY = 0;

    if(handler.isDown() && KeyInput.pressed == true) velY = 5;
    else if(!handler.isUp() && KeyInput.pressed == true) velY = 0;

    if(handler.isRight() && KeyInput.pressed == true) velX = 5;
    else if(!handler.isLeft() && KeyInput.pressed == true) velX = 0;

    if(handler.isLeft() && KeyInput.pressed == true) velX = -5;
    else if(!handler.isRight() && KeyInput.pressed == true) velX = 0;
}


texts:
If I have a particle, say in a polar coordinate grid, and I want to apply multiple vectors to it, how can I calculate where it's final position will be given those vectors?

Ex. Imagine there's a force represented as a vector, that moves the particle a radius magnitude of 8 at an angle of 45°. Another vector that acts on it at the same time, at magnitude 3 at 90°. How would I calculate the final position of the particle?


texts: Unity: Is there any way for a button to call a function of all clones?

texts:
I really don't know off hand. I've got a few ideas but I'm not at my PC to test it.

like ButtonisPressed > Clone script etc()

//on every gameobject clone
void etc() {
  i = 2;
}

That way all i's in the clones will be 2. I want it to work like pacman, if all the clones(or ghosts) have i = 2 then they enter their blue state and they change colors. Except I want to call etc() function with a button
Thanks in advance. If no one figures it out, I will report back later (~12hrs)


texts:
I'm currently working on a scriptable questing system. As for scripting, I will probably use JavaScript, but I'd appreciate some help with the design of the system. My first attempt essentially resulted in something which was way too complicated to script, and wasn't plausible at all.

My objectives for the system are as follows:

Branchable (probably not a real word) - So there can be multiple different outcomes for the same objective depending on what the player chooses, and their choices will affect which quests they move onto next.
Not ridiculously complicated.

Obviously, I'm not here to be given a list of everything I need to do. Ideally, I'd like some tips on how to store progression and a basic idea of how branching would work.

Some details: I'm writing in Java, and I ideally want there to be many options in terms of types of objectives. I can implement these easily enough - my problem is more the structure of a quest. I'm writing the quest system on top of an already existing game - said game uses LWJGL and does it's own engine-stuff, it doesn't use an engine.


texts:
I recently posted a question about how to technically represent a generated terrain similar to the game kingdoms and castles.

I got some great advice and decided to create a 1x1 cube at each coordinate since I will have very small maps, for now 50x50.

I wrote some code to generate terrain,  this is super basic atm and simply instantiates either grass or water tiles depending on the noise value at the coordinate:

public static class Noise
{

    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, float scale)
    {
        float[,] noiseMap = new float[mapWidth, mapHeight];

        if (scale <= 0)
            scale = .0001f;

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                float sampleX = x / scale;
                float sampleY = y / scale;

                float perlinValue = Mathf.PerlinNoise(sampleX, sampleY);
                noiseMap[x, y] = perlinValue;
            }
        }

        return noiseMap;
    }
}

public class MapGenerator : MonoBehaviour
{
    public int mapWidth;
    public int mapHeight;
    public float noiseScale;

    [Space]
    public GameObject grassTile, waterTile;

    public void GenerateMap()
    {
        float[,] noiseMap = Noise.GenerateNoiseMap(mapWidth, mapHeight, noiseScale);

        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapHeight; y++)
            {
                if (noiseMap[x,y] >= .3)
                    Instantiate(grassTile, new Vector3(x, 0, y), Quaternion.identity);
                else
                    Instantiate(waterTile, new Vector3(x, -1, y), Quaternion.identity);
            }
        }
    }
}

It generate something like this:

Now this obviously does not look like a realistic landscape. My question is, how do I decide which values should represent water, and which should represent grass, in order to get a landscape that makes sense?

What I would like my landmass to look like something that has lakes and maybe rivers, instead of these random puddles you see in the image above, more something like this:

EDIT:

Setting a higher scale value lead to this:


texts: What C++ libraries can be used in game development

texts:
I'm currently in the planning stage for my next game, and since I've been away from C++ for a while I have some questions about helpful libraries. I plan on making a 2D game with SDL, constructing my own simple 2D engine. I plan on making this game for the PC.

What libraries would you recommend to make this process easier?

What about unittests?

What about an enforce operator to throw exceptions?

int a = 1;
enforce(a == 2); //Throws an exception,

Specifically, i'm looking for general purpose libraries, that implement that make my life easier (like boost). Also, a helpful library for physics/collision, AI, XML file parsing (specifically working with the Tiled map editor), and any others that you guys have used that are useful in a 2D game.


texts: How to apply linear drag to a velocity vector?

texts:
I have built my own movement code for my character as I want to make smooth movement. (This project is just a character and a floor/wall for testing).

The code seems to work fine, but I of course need to apply my own drag somehow. I've tried many ideas for this, and tried to read around a lot. But I can't work out if this code I made is frame dependant or not.

I am getting 120fps in Unreal editor for example (and my monitor is 144hz if that affects it), but what if someone played my game and was on 60fps, or another number.

After many hours I came up with the code below, and I did even go on the calculator and try to test with various numbers, but sadly I'm no expert mathematician, I wasn't sure if the figures I got meant it was good or bad.

Anyway, here is the move method, pretty self-documenting. With the drag part at bottom. Does this drag formula apply consistent drag for the character over any frame rate?

void APostie::Move()
{
float DeltaTime = GetWorld()->GetDeltaSeconds();
FHitResult Hit;

CurrentVelocity.X = FMath::Clamp<float>(CurrentVelocity.X + (InputAxisVector.X * WalkForce), -MaxWalkSpeed, MaxWalkSpeed);
CurrentVelocity.Y = FMath::Clamp<float>(CurrentVelocity.Y + (InputAxisVector.Y * WalkForce), -MaxWalkSpeed, MaxWalkSpeed);
FVector ForwardMovement = GetActorForwardVector() * CurrentVelocity.X;
FVector SidewaysMovement = GetActorRightVector() * CurrentVelocity.Y;
FVector Velocity_Localised = ForwardMovement + SidewaysMovement;

float r = 1;
FVector DeltaMovement = Velocity_Localised * (FMath::Pow(r, DeltaTime) - 1.0f) / FMath::Log2(r);

AddControllerYawInput(LookAxisVector.X * LookSpeed);
GetMovementComponent()->MoveUpdatedComponent(Velocity_Localised, GetActorRotation(), true, &Hit);

// Apply drag
CurrentVelocity *= (1 - WalkDrag) * (1 - DeltaTime);
if (CurrentVelocity.IsNearlyZero())
{
    CurrentVelocity = FVector::ZeroVector;
}
}

NOTE: WalkDrag is a uproperty set to 0.01f.

Also, I do of course realise I need to clamp the velocity and to handle hits so velocity is set to zero if I hit walls etc. I'm doing that now, but meanwhile still unsure about this drag formula.

UPDATE: I've tried to take on board DMGregory's help. Here is what I came up with:

void APostie::Move()
{
float DeltaTime = GetWorld()->GetDeltaSeconds();
FHitResult Hit;

CurrentVelocity.X = FMath::Clamp<float>(CurrentVelocity.X + (InputAxisVector.X * WalkForce), -MaxWalkSpeed, MaxWalkSpeed);
CurrentVelocity.Y = FMath::Clamp<float>(CurrentVelocity.Y + (InputAxisVector.Y * WalkForce), -MaxWalkSpeed, MaxWalkSpeed);
FVector ForwardMovement = GetActorForwardVector() * CurrentVelocity.X;
FVector SidewaysMovement = GetActorRightVector() * CurrentVelocity.Y;
FVector Velocity_Localised = ForwardMovement + SidewaysMovement;

float r = WalkDrag;
FVector DeltaMovement = Velocity_Localised * (FMath::Pow(r, DeltaTime) - 1.0f) / FMath::Log2(r);

AddControllerYawInput(LookAxisVector.X * LookSpeed);
GetMovementComponent()->MoveUpdatedComponent(DeltaMovement, GetActorRotation(), true, &Hit);

// Apply drag
CurrentVelocity *= FMath::Pow(r, DeltaTime);

}


texts: (Game Maker Studio) How do I make a high score system?

texts:
For my game, I want a way to make the game remember the top score. I know how to make the game save, I just need a way to save a high score.

This is my current system, that has not been working:

If next room exists >
If score is larger than health >
Set the health to score >
    highscore_add(global, score);
    highscore_value(health)

This has an output of nothing.

I would really appreciate some help!


texts:
I'm trying to implement 2D platformer game inspired by N game. But the problem is I have no idea how to implement something like this:

 and

I have two ideas of how this could be implemented, but I don't know if they are somewhere near truth:

Pick two nearby pixels of the surface, draw a line between them and then rotate player so his height was perpendicular to that line.
Check if the bottom-left pixel is touching surface and bottom right is not, rotate player so bottom-right pixel would touch the surface too.


texts: How do I interpolate an object from point A to B such that it accelerates, overshoots, and bounces back to target position?

texts:
How The Game Works
You grab and drag an object around. Once you let go, it interpolates to a certain, variable position, and that's what I'm trying to do here.
Problem Description
I'm talking about vectors, but simplifying that to ordinary numbers for the sake of an example, if A is 0 and B is 1, the object would go something like this:

0.0
0.2
0.5
0.9
1.3
0.9
1.1
1.0

What I've Tried
private IEnumerator GoTo(Vector2 endPosition) {
    float elapsed = 0;
    float duration = 1f;

    while (elapsed <= duration) {
        transform.position = Vector2.LerpUnclamped(transform.position, endPosition, animCurve.Evaluate(elapsed / duration));
        distance = CalculateDistance(transform.position, endPosition);
        elapsed += Time.deltaTime;
        yield return new WaitForEndOfFrame();
    }
}

Where animCurve is:

The highest point is approx. 1.3, and the plot converges to 1.0 from there.
Result
This doesn't work at all. Unless something's wrong with Unity's Vector2.LerpUnclamped(), I'm lost.


texts: Saving precomputed data about game objects in Unity3D

texts:
In my Unity3D game I have blocks of the environment that are placed by script into the scene. Each block has some bezier paths created with this asset. I can access all points of the paths when I place the block into the scene but I would like store start and end points of these paths somewhere and be able to retrieve this data before I place the blocks into the scene.

The only solution I can currently think of is creating a scene which would run a script that would place all these blocks into the scene, one after another, store the data in a file and this file would then be loaded before the game starts. However this solution feels kinda hacky.

Is there any better way to obtain and store this data in Unity? Is it even possible to create the file and load it when the game starts and also add it to the built game?


texts: Farseer: Difficulties with implementation of DebugView

texts:
I added the project "Farseer Physics Engine 3.3.1 HelloWorld XNA\DebugView XNA\DebugView XNA.csproj" to my solution explorer in Visual Studio. In addition, I added a reference to my project and the "using FarseerPhysics.DebugViews;" to my class.

But DebugView is still not working. I tried this code but I always get an error message and a warning. I found the code in a Farseer discussion:
https://farseerphysics.codeplex.com/discussions/275582

Error message:

'FarseerPhysics.DebugViews.DebugViewXNA' does not contain a definition for 'DebugPanel' and no extension method 'DebugPanel' accepting a first argument of type 'FarseerPhysics.DebugViews.DebugViewXNA' could be found (are you missing a using directive or an assembly reference?)

Warning:

The referenced component 'DebugView XNA Content (Content)' could not be found.

What is this DebugPanel? What is wrong?

What should I change in my code?

Code:

World world;
DebugViewXNA physicsDebug;
DebugViewXNA DebugViewFlags;
physicsDebug = new DebugViewXNA(world);
physicsDebug.AppendFlags(DebugViewFlags.DebugPanel);
physicsDebug.DefaultShapeColor = Color.White;
physicsDebug.SleepingShapeColor = Color.LightGray;
physicsDebug.LoadContent(GraphicsDevice, Content);

Drawing DebugView:

 // calculate the projection and view adjustments for the debug view
        Matrix projection = Matrix.CreateOrthographicOffCenter(0f, graphics.GraphicsDevice.Viewport.Width / _displayUnitsToSimUnitsRatio,
                                                         graphics.GraphicsDevice.Viewport.Height / _displayUnitsToSimUnitsRatio, 0f, 0f,
                                                         1f);
        Matrix view = Matrix.CreateTranslation(new Vector3((_cameraPosition / _displayUnitsToSimUnitsRatio) - (_screenCenter / _displayUnitsToSimUnitsRatio), 0f)) * Matrix.CreateTranslation(new Vector3((_screenCenter / _displayUnitsToSimUnitsRatio), 0f));
        // draw the debug view
        physicsDebug.RenderDebugData(ref projection, ref view);


texts: Animation import: What am i doing wrong?

texts:
I need some help with an Animation that i want to import with Humanoid type (made in Blender).
Essentially i made an animation in blender with IK/FK (Rigify, with a bone for the sword, and IK to the hand). This is the preview in blender: https://i.gyazo.com/4f197c5e0ff1b291b45399fb4325ffc9.mp4
And this is when i import and set the animation with humanoid (activated the mask on the sword bone, parented with the root bone): https://i.gyazo.com/b042c29895be8e3db93edaa22e2a3665.mp4
In Blender i keyed IK and FK swith with the slider of Rigify, so i can move the hand without sliding. What i'm doing wrong? This is the Blender Rig (Rigify) with the sword bone https://i.gyazo.com/00a1f9f523e67c0371b7f00e48c58ae9.mp4


texts: What are some good podcasts for game developers to listen to?

texts:
This could include specific game dev, general dev or general game podcasts.

Please provide a brief description along with links.


texts: How are deterministic games possible in the face of floating-point non-determinism?

texts:
To make a game like an RTS networked, I've seen a number of answers here suggest to make the game completely deterministic; then you only have to transfer the users' actions to each other, and lag what's displayed a little bit in order to "lock in" everyone's input before the next frame is rendered.  Then things like unit's positions, health, etc. don't need to be constantly updated over the network, because every player's simulation will be exactly the same.  I've also heard the same thing suggested for making replays.

However, since floating-point calculations are non-deterministic between machines, or even between different compilations of the same program on the same machine, is this really possible to do?  How do we prevent that fact from causing small differences between players (or replays) that ripple throughout the game?

I've heard some people suggest avoiding floating-point numbers altogether and using int to represent the quotient of a fraction, but that doesn't sound practical to me - what if I need to, for example, take the cosine of an angle?  Do I seriously need to rewrite an entire math library?

Note that I am mainly interested in C#, which as far as I can tell, has exactly the same problems as C++ in this regard.


texts:
I have an fps camera, and i am representing rotation with quaternions.  every frame i grab how much the mouse moved that frame and then i simply do

Quat DeltaQ = Quat::CreateRotationXYZ(MouseYDelta, MouseXDelta, 0);
m_CurrentRotationQ = DeltaQ * m_CurrentRotationQ;

however, everything works until i rotate 90 degrees to the right.  when i do that i cannot rotate up and down.  also, moving the direction i am facing works, however, depending on where i am looking strafing left and right moves me in different directions,  I've tried many things such as reversing order of multiplication, i'm really at a loss.  Any help would be greatly appreciated.


texts: Draw LineRenderer gradually, rather than all at once

texts:
I'm drawing a line with a LineRenderer. It works, but now I would like it the line to be drawn gradually, instead of appearing all at once.
How can I modify my code to achieve this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LineController : MonoBehaviour
{

    private LineRenderer Ir;
    private Transform [] points;

    private void Awake(){

        Ir = GetComponent <LineRenderer>();
    }

    public void SetUpLine (Transform[] points){
        Ir.positionCount = points.Length;
        this.points = points;
    }

    private void Update (){
        for (int i = 0; i < points.Length; i++) {
            Ir.SetPosition(i, points[i].position);
            Debug.Log (points[i].position);
        }

    }
}


texts: How to fill a canvas with triangles that are seemingly random?

texts:
Given a canvas say, 1000 X 1000 unit. I would like to fill the canvas with triangles. The triangles can be of any type right angle, equilateral...etc. To avoid big chunks of triangles lets say all triangles should be of some area say, 40 unit^2. Any suggestions will be appreciated, thank you.

I'm trying to draw something like this:


texts: Gluing Model and View Data Together But Separating Concerns

texts:
I've built a couple of 2D games that are roughly MVC; that is, the main game data and logic are separated into the model (and possibly controllers), and I have a bunch of screens/states that just pull stuff from the model class and draw that on screen.

This is not a complete separation, because things like size, collision detection, etc. tend to be view concerns and not model concerns.

In any case, I have a difficult time "gluing" together models and views. Is there a good way to do this, while still preserving the separation of concerns?

Let's say I'm working with a Sprite class to represent an image, and I have a Player class representing my player (X, Y, number of lives, running/walking, etc.). How do I associate them together?

For example, Player can be a subclass of Sprite, or can contain an instance of Sprite (or vice-versa), or I can have a third class (PlayerModelView) that contains an instance of both Player and Sprite, or something else entirely.

(I've tried the latter approach, but it usually ends with a lot of type conversions and the model checking with the view about collisions.)


texts: Client/Server Object updates seems to run at different speeds

texts:
i have been playing around with the NetworkPrediction sample from Microsoft. Trying to adapt it to use gameTime. The client is running without fixed TimeStep and the server is custom C# and updates a lot faster than client.

Both client and server runs this code at update:

protected void UpdateState(ref ShipState state, GameTime gameTime)
    {
        if (turnRightAcceleration)
            state.Rotation += (this.RotationSpeed * (float)gameTime.ElapsedGameTime.TotalMilliseconds);
        else if (turnLeftAcceleration)
            state.Rotation -= (this.RotationSpeed * (float)gameTime.ElapsedGameTime.TotalMilliseconds);

        Vector2 shipForward = new Vector2((float)Math.Cos(state.Rotation),
                                          (float)Math.Sin(state.Rotation));

        if (trustAccelerating)
            state.Velocity += ((shipForward * this.TrustSpeed) * (float)gameTime.ElapsedGameTime.TotalMilliseconds);

        // Update the position and velocity.
        state.Position += (state.Velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds);
    }

This seems theoretically correct, every time a value is increased or decreased its affected by ElapsedGameTime.

And this is my Server Pump:

    public void Run()
    {
        foreach (GameServerComponent component in this.Components)
            component.Initialize();

        Console.WriteLine("Server running...");

        //DateTime serverStart = DateTime.Now;
        //DateTime lastUpdate = DateTime.Now;

        Stopwatch sw = Stopwatch.StartNew();
        TimeSpan lastTime = sw.Elapsed;
        GameTime gameTime;

        while (!exit)
        {
            TimeSpan currentTime = sw.Elapsed;
            TimeSpan elapsedTime = currentTime - lastTime;
            lastTime = currentTime;

            gameTime = new GameTime(currentTime, elapsedTime);

            foreach (GameServerComponent component in this.Components)
                component.Update(gameTime);
        }

        sw.Stop();
    }

This seems theoretically correct as well. Unless there is something about time management in .NET and XNA, but i cant find anything indicating it.

But the server and client updates at different rates, and the further you get from Vector 0,0 the greater the difference becomes and close to 0,0 it works quite well.
But at Vector2(-1387865f, -1158338f) the "Ship" is barley able to move. I believe this tells me the server "Clock" is running slower than the client (the ship moves slower on server than on client), but i dont understand why it would be more prominent further away from 0,0 (makes me think its the UpdateState() function I need to look at)

I dont know what to test next and I have no idea how to fix this behavior.

Please, i need ideas. Or even better, can you see something obvious wrong with the code i have?

Thank you.

Update:
This are the results from some measurements, recommended from William 'MindWorX' Mariager. Im currently trying to throttle the server to get closer to the clients updates. And i think i need to look at some performance from the client as well (later), since it seems it runs slower than 60fps atm. Ill update with results.

Server
updateCount             252092674

gameTime.TotalGameTime          {00:09:59.9810854}

avgElapsed.TotalMilliseconds        0.0021000000000000003

(float)avgElapsed.TotalMilliseconds 0.0021

Client
updateCount             24027

gameTime.TotalGameTime          {00:09:55.5527941}

avgElapsed.TotalMilliseconds        24.03

(float)avgElapsed.TotalMilliseconds 24.03


texts: Im currently making a game on unity, and in the game i want to make quest system to be flexible, as the game world is generated randomly. I also want to make it easy to create quests for myself and possibly modders. So i want to make a menu for creating quests, however i couldnt find any info on how to make node editor window in unity(like shader graph, vfx graph, etc.). How do I do this?


texts: Using modified copyrighted music in non-commercial games

texts:
Background: I'm making a retro style game for both fun, and an unofficial contest.

I have bought a song, song X. However, I then found notation for song X, and all the instruments. So basically, it's a program recreating song X in a sense.

I took the notation, and used another program to make it sound like a chiptune does (just for the fun of it, and it sounds good :P). However, I would like to use this in my game. It's non-commercial, but is this allowed? I would've said yes, because I'm not actually using the original, copyrighted song.

I think the main point is can I:

Use the music with no reference to the author
Use the music with a reference, since it's non-profit.
Not use the music at all since the melody and rhythm is copyright.


texts:
I have a problem rendering my pixel art sprites properly in Unity.
So far I have one character in a sprite-sheet I made, with frames of size 64x64. The actual sprite is roughly 32x32 but I left room for movement in animations.
I import the sheet following pixel perfection procedures I found on the internet using these settings:

As for the orthographic camera I set its size using this formula:

orthoCameraSize = screenHeight / (2 * 32)

If I zoom on the sprite in scene it looks fine but when in game it gets rendered quite poorly (in game / in scene pics below):

What could be the source of the problem? I applied every good practice advice I could find on the web...
Thanks for your help!!!!


texts: How can I blend an animated character with ragdoll physics collisions?

texts:
I'm trying to make an effect that a ragdolled character controlled by an animator also affected by the physics collisions. Similar to this game: Crazy Shopping.

The problem is animator controller overrides every change that happens in the Fixed Update or internal physics update (even when the animator update mode set to Animate physics).

I think this can be achieved by some how changing the order of execution of the animator so it can happen before physics update. This way physics can affect the animated object. There are solutions like using a second object which contains the ragdoll and in the LateUpdate you can set the positions and rotations of the animated object which works ok but not the thing in my head.

ActiveRagdoll by MetalCore999 is also a really great work which i would love to learn how it works in behind.

How can i achieve this? i don't even know if my solution would work properly?

Do you have any suggestion or a different way of thinking. I would really appreciate a road map on this.


texts: Libgdx fbx converter doesn't write meshes to g3dj file

texts:
LibGDX FBX converter doesn't write meshes nor materials to g3dj file.

This happens with blender 2.8 when exporting model to FBX then converting it to g3dj. meshes will result in an empty block.

2.8 blender settings

and when converting...

g3dj file..

{
   "version": [  0,   1],
   "id": "",
   "meshes": [],
   "materials": [],
   "nodes": [
       {
           "id": "Cube",
           "rotation": [-0.707107, -0.000000,  0.000000,  0.707107],
           "scale": [ 10.000000,  10.000000,  10.000000]
       }
   ],
   "animations": []
}

I tried to convert a fbx written with blender 2.76 with these settings...

and meshes and materials are written in g3dj file successfully. I'm thinking this has to do with FBX version, but it seems you can't change FBX version in blender 2.8


texts: Unity provides wrong Input value if game is started with bumpers pressed down

texts:
As the title states I am having an issue with the following. It is a pretty specific edge case but it is something I can't work around.

In Unity I have created two Axes to allow me to check the value of the of the left and right bumpers on an Xbox controller. The problem I am having is the controller I am using is a special product where by default the left and right bumper are always on. This is intended on the controller and is definitely not changeable. The issue here is that because the controller has the bumpers pressed in by default when Unity is launched it reads the input of those buttons with a value of 0 instead of 1 (as I have the controllers set to provide a positive input).

I've tested this with a normal Xbox controller by manually pressing the trigger in before I launch the game and I get the same results so I can confirm that it is a Unity thing and not a controller issue. The only way to fix the controller's input is to manually refresh the bumpers (which are attached to sensors in this case).

This is currently not an acceptable way for me to refresh the device I just need to get the devices correct input immediately. Is there a way I can, in code, not have the game recognize the controller until I specify? The reason for this is if I plug my device in AFTER the game starts I get the correct values.

This game will only ever be run on Windows so I would be open to coding up an OS level script that utilizes some of the Windows functions.

EDIT: I thought I should add I have tried sending visualized input to the device via code and this has not fixed the issue.


texts: I set two sprites with different widths on my scene, both on position x = 0, but the smaller one stays exactly at the middle of the bigger one. So, is the position x = 0 relative to the middle position of the sprites? Is there anyway I can set it to the top left (so my calcs would be easier)?


texts: How To Make My First Person Controller turn left and right in unity 5

texts:
I want my first person controller to turn left and right instead of just moving straight on that axis.

i have a 3d environment setup in "unity 5" and i am working with the "first person controller" script in unity 5 by default it moves my camera forward,back,left and right what i want is to change the left and right so that it turns the camera instead of moving straight over.


texts: Z - Axis value is changing if I move the Game Object in X - Axis in Unity

texts:
I am on a small game project . Everything was just fine , but now I have some wired problem . That is Game Object movement . If I move the game object in X - Axis using the gizmo , the value of Z - Axis is changing . And if move in Z - Axis the value of X - Axis is changing . This is totally wired to me .

The game object is Empty Game Object and It is in the scene as a Child . Its position is as follow :-

One Game Object
      Another Game Object
           My Empty Game Object which is acting wired

Here are the screen shots :-

So why it is behaving so wired ? What is the problem ?

I hope you will help me to figure it out .

Regards

NB :)


texts: How to create an endless scrolling background?

texts:
I need to add a scrolling background to a my game, the image is 512x512px. It's for a car game with two way traffic and I want to be able to cross over to the opposite side and drive against the traffic too. The game is in portrait mode and I use cocos2d.

How can I make this in the best possible way?


texts:
In lieu of a typical implementation of entity-component systems, I've gone the data-oriented route described by Jason Gregory in Game Engine Architecture.  This works really well for common properties that need to be present in practically every entity, like position, model information, and health.

// Common properties
namespace Entity
{
    Vector position[MAX_ENTITIES];
    int health[MAX_ENTITIES];
    Model::ID model[MAX_ENTITIES];
}

But what about when it comes to specific information like character status, AI behavior modifiers, and NPC descriptions?  Only a handful of entities need this kind of information: who would expect a barrel to give out quests?  It needs to be discrete for each entity, so flyweighting is ruled out.

// Rare properties
namespace Entity
{
    // Character stats
    int strength[MAX_ENTITIES];
    int intelligence[MAX_ENTITIES];
    int charisma[MAX_ENTITIES];

    // AI behaviour
    int aggressiveness[MAX_ENTITIES];
    int recklessness[MAX_ENTITIES];
}

Should I just grit my teeth and make every entity a blob of the same data?  Or is there something else I can do to create distinctions between entity types?

Edit:

Here's a method I'm now considering.  Hopefully I can program the systems to make use of this layout while still avoiding memory problems.

// Common entity data
bool            Entity::active      [MAX_ENTITIES];
Vector          Entity::position    [MAX_ENTITIES];
Quaternion      Entity::orientation [MAX_ENTITIES];
Vector          Entity::scale       [MAX_ENTITIES];

// Entity handles
Model::ID       Entity::model       [MAX_ENTITIES]; // Index into the Model::X properties
NPC::ID         Entity::npc         [MAX_ENTITIES]; // Index into the NPC::X properties
Script::ID      Entity::script      [MAX_ENTITIES]; // Index into the Script::X properties
Status::ID      Entity::status      [MAX_ENTITIES]; // Index into the Status::X properties

// Models
Material::ID    Model::material     [MAX_MODELS];
Mesh::ID        Model::mesh         [MAX_MODELS];
Skeleton::ID    Model::skeleton     [MAX_MODELS];

// Materials
Texture::ID     Material::colorMap  [MAX_MATERIALS];
Color           Material::diffuse   [MAX_MATERIALS];
Texture::ID     Material::normalMap [MAX_MATERIALS];
Color           Material::specular  [MAX_MATERIALS];
Shader::ID      Material::shader    [MAX_MATERIALS];

// You can see where this is going...

The benefits of this are that you only need to specify the data for the components you need, and it works well with my resource systems (which operate via handles).  It also allows me to process each mesh in the same way, each animation in the same way, etc.

I'll post more if I run into any issues.


texts:
I currently am trying to mask some sprites.  Rather than explaining it in words, I've made up some example pictures:

 The area to mask (in white)

 Now, the red sprite that needs to be cropped.

 The final result.

Now, I'm aware that in XNA you can do two things to accomplish this:

Use the Stencil Buffer.
Use a Pixel Shader.

I have tried to do a pixel shader, which essentially did this:

float4 main(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 tex = tex2D(BaseTexture, texCoord);
    float4 bitMask = tex2D(MaskTexture, texCoord);

    if (bitMask.a > 0)
    {
        return float4(tex.r, tex.g, tex.b, tex.a);
    }
    else
    {
        return float4(0, 0, 0, 0);
    }
}

This seems to crop the images (albeit, not correct once the image starts to move), but my problem is that the images are constantly moving (they aren't static), so this cropping needs to be dynamic.

Is there a way I could alter the shader code to take into account it's position?

Alternatively, I've read about using the Stencil Buffer, but most of the samples seem to hinge on using a rendertarget, which I really don't want to do.  (I'm already using 3 or 4 for the rest of the game, and adding another one on top of it seems overkill)

The only tutorial I've found that doesn't use Rendertargets is one from Shawn Hargreaves' blog over here.  The issue with that one, though is that it's for XNA 3.1, and doesn't seem to translate well to XNA 4.0.

It seems to me that the pixel shader is the way to go, but I'm unsure of how to get the positioning correct.  I believe I would have to change my onscreen coordinates (something like 500, 500) to be between 0 and 1 for the shader coordinates.  My only problem is trying to work out how to correctly use the transformed coordinates.

Thanks in advance for any help!


texts: Call a BlueprintImplementableEvent from c++ in unreal editor?

texts:
I created a custom actor:

BPTest.h:

#include "GameFramework/Actor.h"
#include "BPTest.generated.h"

UCLASS(Blueprintable, BlueprintType)
class ABPTest : public AActor
{
    GENERATED_BODY()

public:
    ABPTest();

    virtual void BeginPlay() override;

    UFUNCTION(BlueprintImplementableEvent, meta = (DisplayName = "Custom event"))
    void CustomEvent(float Value);
    void CustomEvent_Implementation(float Value);
};

BPTest.cpp:

#include "ProBuilderPrivatePCH.h"
#include "BPTest.h"

ABPTest::ABPTest()
{
    PrimaryActorTick.bCanEverTick = true;
}

void ABPTest::BeginPlay()
{
    Super::BeginPlay();
    CustomEvent(0.f);
}

void ABPTest::CustomEvent_Implementation(float Value)
{
    UE_LOG(LogTemp, Warning, TEXT("CustomEvent_Implementation: %f"), Value);
}

I then created a blueprint from this actor class.

I added an instance of this blueprint actor in my level.

I would like to call this custom event from c++ in the editor, not when the game is started.

I tried this in a custom editor mode (extending FEdMode):

bool FProBuilderEdMode::InputKey(FEditorViewportClient *ViewportClient, FViewport *Viewport, FKey Key, EInputEvent Event)
{
    for (TActorIterator<ABPTest> ActorIterator(GWorld); ActorIterator; ++ActorIterator)
    {
        ActorIterator->CustomEvent(1.f);
    }
    return FEdMode::InputKey(ViewportClient, Viewport, Key, Event);
}

but it does not work. I assume the game has to be started (hit play) in order for the blueprint event to be taken into account. Is my assumption correct?

How can I call a blueprint function from c++ when the game is not started (Is it even possible)?
I have seen UObject::CallFunctionByNameWithArguments but it seems dirty.


texts: Project rendering onto a polygon in the scene

texts:
I have a function that renders a simple OpenGL scene. I want to display this scene on a polygon within another scene, without the function having to know about it. For example, to display the scene on the red polygon indicated:

I can set up the projection and modelview matrices to render to a small rectangle on the screen, but that doesn't work in a case like the image shown, where the target polygon is transformed and is no longer a rectangle on the screen. Is it possible to render to a non-rectangular target like this? The target is defined by four vertices, and I'm just not sure how to put those into the matrices.

I am aware of VBO/FBO functions that can render the sub-scene to a texture, which could then be mapped onto the polygon. However, this would be a bit more work as I'd have to add support for these functions to LuaGL, and I get the feeling it'd be slower than simply altering the display matrices - if it can even be done that way.


texts: Strange anomalies when using WinForms with XNA

texts:
I haven't seen any questions related to my issue, and this leads me to believe I'm missing something minor, however;

The Problem

I'm creating a game that is effectively launched from a windows form. Consider the following code.

static void Main(string[] args) {
        main = new TestGame(); // The Game class.
        menu = new Menu(main); // The form.

        while (true) {
            if (menu.ShowDialog() == DialogResult.OK) {
                if (menu.ShouldStartGame) {
                    main.RunGame( /* Some params */ );
                } else {
                    ExitGame();
                    break;
                }
            }
        }
    }

This loop works fine. My issue lies in the form itself. Firstly, DialogResult does not trigger at all. When the result from menu.ShowDialog() is printed, its result is "Cancel" which is not the option set for the button (OK.) As well as this, picture boxes, the form background colour and other such controls do not work properly. And the form appears to have a UI style from Windows versions before or during XP. Is this a known issue or am I missing something?


texts: How do I record scripted rotation changes in animation file?

texts:
I can create an animation file by clicking "Animation", then selecting a gameobject, then press record and then change bone rotations in the Inspector.
The animation window will be notified about the bone rotation changes and add this to the animation file like this:

This works fine as long as the Inspector is used to change the bone rotations.
Bone rotations done by a script are not recorded.
Is there a trick to record these bone rotations via script anyways?
For example using something like (pseudo-code) this? ->
rShoulder.rotation.dirty = true;

For your interest, I have attached the script that I use to rotate the bones and which are not recorded. This script works perfectly fine, but it doesn't trigger animation changes:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyPlayer : MonoBehaviour
{
    public Transform Target;

    private void OnGUI()
    {
        if (GUI.Button(new Rect(0, 70, 50, 30), "Transfer rotations to other model with same rig"))
        {
            List<Transform> nTheseTransforms = new List<Transform>();
            Helpers.GetAllChildren(this.transform, ref nTheseTransforms);

            List<Transform> nTargetTransforms = new List<Transform>();
            Helpers.GetAllChildren(Target, ref nTargetTransforms);

            foreach (Transform nThisTransform in nTheseTransforms)
            {
                foreach (Transform nTargetTransform in nTargetTransforms)
                {
                    if (nThisTransform.name == nTargetTransform.name)
                    {
                        nTargetTransform.localRotation = nThisTransform.localRotation;
                        break;
                    }
                }
            }
        }
    }
    public static void GetAllChildren(Transform parent, ref List<Transform> transforms)
    {
        foreach (Transform t in parent)
        {
            transforms.Add(t);
            GetAllChildren(t, ref transforms);
        }
    }

}


texts: How can I get almost pixel perfect collision detection in a multiplayer game?

texts: I'm currently working on a multiplayer game for iPhone. The problem I have, as with all multiplayer games, is that the other user will always see everything at a non-constant delay. The game I'm making needs to have an almost pixel perfect collision detection, but 1 or 2 pixels off is not that big of a deal. How can I possibly get this working? I guess I could just set local player to also be at X ms delay. However this will probably just be worse and feel sloppy when the user input. I know this problem is probably something network programmers deal with everyday and I would be glad if someone could give me a possible solution for this.


texts: How can I rotate a bitmap without D3D or OpenGL?

texts:
I've just figured out on my own how to scale a portion of a bitmap using PutPixel. I would like to know the mathematical theory behind rotating a bitmap on my own, using per-pixel operations like PutPixel.

I am not interested in using OpenGL or Direct3D to accomplish this, I'd like to know what the fundamental math and programming technique behind the operation is?


texts: Should I have a public development blog?

texts:
Should I keep a public development blog for a game I'm creating?

What are the benefits and issues of this activity?


texts: Functional reactive programming (FRP) in games. Some doubts and thoughts

texts:
These days, I'm doing some research on component-based entity systems. I had a first approximation, using a blackboard pattern at the entity level, and with components sharing this blackboard to do communication.

Doing this research, I found an entity framework called Artemis, that follows a FRP structure for the entity management. The idea seems pretty good, and I'm thinking of integrating in to my engine. I have some questions that need to be solved to fully understand this "odd" architecture:

In my first approximation, the way components shared data is pretty straight forward, following the blackboard pattern. How should this be done, following FRP? It seems each system would be the ones holding all dependencies to the components, making components totally decoupled. If the collision system needs to know about physic component, movable system, etc; the collision system would import all of these components, and do all needed work with them. Is that right?
Would each system be a homogeneous or heterogeneous component container? I guess its system has to be homogeneous, related to the component type it holds, because the system needs to know the component data, to play with it during updates. This leads me to next question:
Does this architecture lead to too many system/components?
How does an event system fit in to this structure? I usually have slot/signals in game objects, for this, but it seems there is no "Entity" concept with the Artemis structure.


texts: which is more performant particles_system or animation_player

texts: let's say I wanna make an Aura+Thunder effect , I can achieve the result using the Particles System like this vid: https://www.youtube.com/watch?v=4eMZspcU5Is , or by using AnimationPlayer , but which is more performant if there will be like 15 instance of the Aura+Thunder effect + other effects?


texts:
I want to return a colour for a position t, given an arbitrary number of colour stops - a stop is comprised of a position, and a colour.

Like selecting a colour from a multiple-colour gradient, linearly interpolated between stops.

Positions and point t are floating point numbers and can be negative. Positions and their respective colours are ordered lowest to highest in the arrays.

I would like to avoid conditional statements, as this is for use within a shader.

Code would ideally be in the form:

float3 MultiColorLerp(float positions[], float3[] colors, float t) {
    // Returns the color at the point t.
}


texts: Unity: camera moving up and down for no reason

texts:
I have a standard camera in my scene. With standard I mean the camera you get when you click right mouse > Camera, with no modification except for the transform position and rotation. Then I attached to the camera this simple script:

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

public class CameraController : MonoBehaviour {

public GameObject target;
public Vector3 translationOffset;
public Vector3 rotationOffset;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    transform.position = target.transform.position + translationOffset;
    transform.LookAt(target.transform);
    transform.Rotate(-rotationOffset);
}

}

the result I have is this:

Why my camera is doing that? It may be worth noticing that everything was working fine, but at some point i clicked on "reimport all assets" and it started this weird behaviour. How can I fix? Thanks a lot.


texts: How can I copy an asset folder programatically depending upon a constant?

texts:
I have a Unity project in which I have 200 games and some 350 scenes. Now I want to make separate builds for each game. All my assets are present in Assets/IgnoredAssets/ABC folder. To include these assets in my current build the assets of the current game (say ABC) needs to be in Assets/Resources/ABC.

I want Unity to take these Assets/IgnoredAssets/ABC files and copy them to Assets/Resources before making build depending upon a constant defined in some file.

I want a kind of automation so that when I mention in my constant file string gameName="ABC"; it automatically picks its assets, paste them in Resources and builds for me.

How can I do this?


texts: Are OpenGL Textures more memory efficient than Android Bitmaps?

texts:
I have a custom application that deals with many Bitmaps tiles that are 256x256 images (png,jpg). I'm currently using the View 2d canvas and bring in all images as RGB_565. Although I'm generally happy with the applications performance, I have features I'd like to add that will require even more map tiles (Bitmaps). I've been thinking about using opengl ES 2.0 but am fairly new to it.

Would opengl Textures be more memory efficient than keeping Bitmaps
around? I assume you can load a Bitmap into a Texture and then
dispose of the Bitmap
Is it an acceptable practice in opengl to dynamically load many
different Textures at runtime?
Do you need to cache Textures or does the GPU handle that for you?


texts: How to convert -1 to 1 coordinate back to screen coordinates?

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


texts: Detecting keys presses between keyboard layouts, operating systems and javascript

texts:
I've recently encountered a few headaches when I tried to detect key presses for a custom game engine to supports Windows, MacOS, Linux, and WebGL.

Naive approach:

At first I naively thought that using GLFW's keycodes instead of scancodes will be the best solution to cover as many operating systems as possible. I later found out that if the player has a different keyboard layout, the keys will be bound all over the place instead of having the WASD keys (regardless of what character they represent) sit together.

Problem #1

So then I moved over to using scancodes. So this works great (other than having a different set of scancodes for each operating system) but it also introduces my first issue. Since scancodes are position based and defined as integers, how will I display to the player what character, for their unique keyboard layout, is currently bound in the game's "Keyboard Settings" dialog. I don't imagine detecting a keyboard layout is plausible (might even be impossible with Javascript since I don't have access to OS calls).

Problem #2

My second issue is when the game is deployed with WebGL. In Javascript the keyCode value is just fed to the browser from the underlying operating system. What this means is I have to check the OS at runtime and remap all the keybinds based on the operating system. This is a nightmare because, if the user has customised keybinds (stored to his cloud profile) that was created on MacOS but then later opened up on Windows, then the code will have to do three remaps in order to, get the OS when keys where customised, then get the current OS, and then the conversion between the two prior to taking into consideration the customised remaps... Is there not a better way?! This would also mean I will have to send all the keycode constants for everything possible operating system to each user. Resulting in a lot of unnecessary boat in the Javascript file.

Just assume?

It seems like the big game engines out there have this issue solved and I am curious how they got around these issues. Do they just assume all players use QWERTY keyboards at the risk possibly frustrating a certain audience until they remap the keys ingame? And do they assume all browser based games are played on Windows, MacOS, and Linux to keep the javascript OS detection to a minimal? (effectively losing mobile players)


texts: LibGDX - How do you load huge spritesheets?

texts:
As we know, there is a GL_MAX_TEXTURE_SIZE on each mobile phone which makes things really hard. I write an app for all mobile devices and I need to load some huge spritesheets combined with 64 frames when each of them has 512x1024 dimensions.

As I tested and read, I should load spritesheets <= 1024 so it will work on all mobile devices including IPhone3 and some old Androids.

If I have a spritesheet 512x1024 with 64 frames, it's dimensions are really, really large - for ex. if the spritesheet has 64 columns, it's with is ~61000 px.

Of course, I can cut it, but it gives me 64 images and I have no idea if this if efiicient of not.

How do you handle things like this? Scaling the graphics down is not an option - it lowers the quality and my game IS QUALITY.

If someone has any experience I would be grateful!


texts:
I'm trying to generate a 2D grid, for use in navigation, where each grid point holds the distance to the nearest obstacle (such as impassable terrain, or a constructed building). So for example, a grid point containing an obstacle would be 0, the grid point next to it would be 1, the next one further away would be 2, etc.

So far I've been able to accomplish this using multiple passes. Each pass, for every grid point, I take the lowest value from all neighbors, and add one. If I want to measure out to a max distance of, say, 10 grid points, I have to make 10 passes, slowly incrementing the most distance grid points.

My question is, is there a way to generate this sort of grid in just a single pass? This grid will be periodically updated during gameplay, and could be very large, so I don't want to be looping over it multiple times if I don't have to.


texts: Unity: "Find" can only be called from the main thread, but moving variables to the Start() function causes other errors

texts:
#pragma strict

 var collided = false;
 var thrust: float;
 var pizza = GameObject.Find("pizza-small").GetComponent.<Rigidbody2D>();

     function Start() {

     }

     //hand + pizza collision detection
     function OnCollisionStay2D(coll: Collision2D) {
         if (coll.gameObject.tag == "Pizza") {
             collided = true;
             Debug.Log("Hand+Pizza");
         }
     }

     function Update() {

     //Input
     if (Input.GetKey(KeyCode.W)) {
         Debug.Log("Up");
         transform.position.y+= 0.2;

         if (collided === true) {
         //Adding force to the pizza
         pizza.velocity = Vector3(0,15,0);
         }
     }
     else if (Input.GetKey(KeyCode.A) || Input.GetKey("left")) {
         Debug.Log("Left");
         transform.position.x-= 0.1;
     }
     else if (Input.GetKey(KeyCode.D) || Input.GetKey("right")) {
         Debug.Log("Right");
         transform.position.x+= 0.1;
     }
     else if (Input.GetKey(KeyCode.S) || Input.GetKey("down")) {
         Debug.Log("Down");
         transform.position.y-= 0.1;
     }
     else if (transform.position.y > -3.5) {
         transform.position.y-= 0.25;
     }
     else {
         collided = false;
     }

 }

Moving the 3 initial variable declarations into Start() removes the "Find can only be called from the main thread" error, but then they cannot be used in the Update() function due to variable scope.

If I declare them initially and then set their values inside of the start function, new errors arise.

 var pizza;

 function Start() {

 pizza = GameObject.Find("pizza-small").GetComponent.<Rigidbody2D>();

 }

If I do that, then when I use:

pizza.velocity = Vector3(0,15,0);

It states that velocity is not a member of "object".

I have no idea how to fix this, as the program works with no changes to my initial code, but does still give the error. This could be causing problems, as the rigidbody2D of the "pizza-small" is pulled toward any non-preexisting colliders that I add.


texts: Replacing a sprite for another on runtime (Unity3D)

texts:
I need to replace the sprite of a face down card for another sprite (of a face up card).

This is the C# script attached to the face down card:

using UnityEngine;
using System.Collections;

public class Entra : MonoBehaviour
{

    public float velocidadDeRotacion = 100.0f;
    public Sprite CartaBase;
    public Sprite CartaDelantera;

    private bool clickActivado = false;
    public void OnMouseDown()
    {
        clickActivado = true;
    }

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {

        if (clickActivado)
        {
            transform.Rotate(Vector3.up * Time.deltaTime * velocidadDeRotacion);
            if (transform.eulerAngles.y >= 90)
            {
                SpriteRenderer Carta;
                Carta = GetComponent<SpriteRenderer>();
                if (Carta.sprite == CartaBase)
                {
                    Carta.sprite = CartaDelantera;
                    transform.Rotate(Vector3.up * Time.deltaTime * velocidadDeRotacion);
                    if (transform.eulerAngles.y >= 0 && transform.eulerAngles.y <=10)
                    {
                        transform.eulerAngles = new Vector3(0, 0, 0);
                        clickActivado = false;
                        return;
                    }

                }
                clickActivado = false;
                return;
            }

        }

    }
}

As you can see, I rotate the card when I click on it, when the angle reach 90º I stop the rotation and change the sprite, from CartaBase to CartaDelantera.

Right now I have two problems.

When the sprite has an angle of 1º or more, the image breaks. I lose the right half of the image from the center to the right border, and I don't understand why.
Using VS2013 as debugger, I make a step by step walkthrough and when it reach

if (Carta.sprite == CartaBase)

it jumps stright to

clickActivado = false;

So, obviously it's not "seeing" the sprite used by the card. Why???

I'm using this script as reference for the change of sprites.

If you don't understand my problem, you can see live here.


texts:
Is it necessary for a game developer (on Android, game consoles, online, or desktop) to display the loading screen to cover unfinished rendered game environments and prevent users from thinking that this game is either lagging or freezing ?

I'm thinking if the game runs seamlessly, then, I don't need to add loading screens since it appears to be too showy or takes long for making animated presentations before the game.

Or, if displaying loading screen is a general standard required for each published game, was it okay to "cheat" by displaying a fake loading screen with any certain length of time even though the game renders smoothly? I would like to know why game developers added the loading screen during when the gameplay is started.


texts: How can I build a C++11 vertex attribute class?

texts:
How would you build a flexible and efficient vertex attribute class in C++11? What I have:

Vertex attribute roles for using them in shaders:

enum AttributeRole
{
    VERTEX0,
    TEXCOORD0, ...
    UNKNOWN_ROLE
};

static const char * AttributeRoleName[UNKNOWN_ROLE + 1] = {
    "vertex0",
    "texcoord0", ...
    "unknown role"
};

A class providing vertex attribute type information:

struct AttributeTypeInfo {
    GLint m_nrOfComponents;
    GLenum m_glType;
    GLsizei m_bytesPerComponent;
    GLsizei m_bytesPerAttribute;
    GLboolean m_normalize;
    AttributeRole m_role;

    AttributeTypeInfo(GLint nrOfComponents, GLenum glType, GLsizei bytesPerComponent, GLsizei bytesPerAttribute, GLboolean normalize, AttributeRole role)
    : m_nrOfComponents(nrOfComponents), m_glType(glType), m_bytesPerComponent(bytesPerComponent), m_bytesPerAttribute(bytesPerAttribute), m_normalize(normalize), m_role(role)
    {
    }
};

A class holding a single vertex attribute:

template <typename COMPONENTTYPE, GLenum GLTYPE, size_t NROFCOMPONENTS, GLboolean NORMALIZE, AttributeRole ROLE>
struct Attribute
{
    COMPONENTTYPE m_data[NROFCOMPONENTS]; //attribute data
    static const AttributeTypeInfo m_typeInfo = AttributeTypeInfo(NROFCOMPONENTS, GLTYPE, sizeof(COMPONENTTYPE), sizeof(COMPONENTTYPE) * NROFCOMPONENTS, NORMALIZE, ROLE); //attribute type information
    //... and some access functions...
};

typedef Attribute<GLfloat, GL_FLOAT, 3, GL_FALSE, VERTEX0> Vertex0_V3F;
typedef Attribute<GLubyte, GL_UNSIGNED_BYTE, 4, GL_TRUE, COLOR0> Color0_C4UB;

This is quite comfortable, but now I want to combine vertex attributes in an interleaved attribute format to be used in buffers later:

/// @brief Dual attribute vertex format
template <typename TYPE0, typename TYPE1>
struct AttributeFormat2
{
    TYPE0 m_attribute0;
    TYPE1 m_attribute1;
    static const size_t m_nrOfAttributes = 2;
    static const size_t m_sizeOfAttributes = sizeof(TYPE0) + sizeof(TYPE1);
    static const AttributeTypeInfo m_typeInfo[m_nrOfAttributes];
};

template <typename TYPE0, typename TYPE1>
const AttributeTypeInfo AttributeFormat2<TYPE0, TYPE1>::m_typeInfo[] = {
    TYPE0::m_typeInfo,
    TYPE1::m_typeInfo
};

typedef AttributeFormat2<Vertex0_V3F, Color0_C4UB> Format_V3F_C4UB;

This gets a bit out of hand when you have 3,4,5 or more vertex attributes...

Is there a (variadic) template solution to the problem with C++11 or 14 or can you suggest a better interleaved vertex attribute format class?


texts:
I was wondering how if(GUILayout.Button(..)) actually works internally.
It is a weird construction, since it returns "true" when the user presses the button, but on the other hand, it also creates a button and then just jumps to the next block of code, so this statement doesn't actually block execution. Then again, it's not of a known asynchronous model.
How is this wired internally?


texts: How do I add a border to rectangles using a shader?

texts:
I want to draw some rectangles with a border. Currently I render the fill with glDrawArrays(Triangles, ...) and the border with glDrawArrays(LineLoop, ...). Is there a neater way?

I'm targeting OpenGL 3.3.

Details

Illustrative excerpt:

// vertexBuffer   -> VertexAttribArray(0)
// colorBuffer    -> VertexAttribArray(1)
// texCoordBuffer -> VertexAttribArray(2)

GL.DrawArrays(PrimitiveType.Triangles, 0, 12); // 2 test rectangles

GL.DisableVertexAttribArray(1); //Disable color array
GL.DisableVertexAttribArray(2); //Disable texture array

GL.DrawArrays(PrimitiveType.LineLoop, 0, 6); // First rectangle border
GL.DrawArrays(PrimitiveType.LineLoop, 6, 6); // Second rectangle border
// Lots of draw calls for every rectangle,
// if there are more than the 2 test rectangles...

This works fine, but I don't like having to draw the additional LineLoops for every rectangle. How can I improve this?

Could I do this elegantly with a shader? Something like this:

// VertexArributes

GL.DrawArrays(Triangles, 0, vertices.Length); // Shader does the border

// DisableVertexAttributes

My current shaders

Vertex

#version 330 core

layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;
layout(location = 2) in vec2 texCoord;

uniform mat4 projMatrix;
uniform mat4 worldMatrix;

out vec4 vColor;
out vec2 texCoords[];

void main()
{
  gl_Position = projMatrix * worldMatrix * position;
  texCoords[0] = texCoord;
  vColor = color;
}

Fragment

#version 330 core

in vec4 vColor;
in vec2 texCoords[];

uniform sampler2D tex;

out vec4 fColor;

void main(void)
{
  fColor = texture2D(tex, texCoords[0].st) * vColor;
}


texts: Event-/Input system with SFML: Cannot move diagonally in 2D

texts:
I am a beginner in anything with game development. I written a small prototype in which i can move a square around with the arrow keys. For that i use SFML.

At the moment i experiment around with my Event System: First, to keep things simple, i was polling for the arrow keys using sf::Keyboard::isKeyPressed(), which works fine for this small kind of "game"

// in handleUserInput():
if(Keyboard::isKeyPressed(Keyboard::Left))
{
        player_.moveLeft();
}

// in player the player class:
void moveLeft()
{
    velocity.x = -x_speed; // sf::Vector2f
}

// in my player-class update() method:
void update()
{
// Out of bounds check and so on...
shape.move(velocity);
velocity.x = 0;
velocity.y = 0;
}

With this i was able to move horizontally, vertically and diagonally.

Then i moved to create my "real" EventSystem based on callbacks.
It wraps around sf::Window::pollEvent(). E.g. i register a callback method for the event type sf::Event::EventType::KeyPressed. So i changed my code to first register for the movement keys

event_system_.registerCallback(sf::Event::KeyPressed, [&] (const sf::Event& event)
    {
        switch(event.key.code)
        {
        case sf::Keyboard::Left:
            log->info() << "Moving Left";
            player_.moveLeft();
            break;
        case sf::Keyboard::Right:
            log->info() << "Moving Right";
            player_.moveRight();
            break;
        case sf::Keyboard::Up:
            log->info() << "Moving Up";
            player_.moveUp();
            break;
        case sf::Keyboard::Down:
            log->info() << "Moving Down";
            player_.moveDown();
            break;
        case sf::Keyboard::Escape:
            window_.close();
            break;
        }
    });

The problem i encountered was, that i couldn't move diagonally anymore.
After adding the loggin parts i found out, that when i keep two arrow keys pressed the only event that gets fired over and over again was the key pressed latest (e.g. i try to press Left & Down and pressed the Down-Key slightly later the Down-Event would be captured over and over again and the Left-Event only once).

After that i changed my code not to reset the velocity in my player's update-method and also registered for sf::Event::KeyReleased so that it would reset the x/y-part of the velocity when the corresponding key was released.

event_system_.registerCallback(sf::Event::KeyReleased, [&] (const sf::Event& event)
    {
        switch(event.key.code)
        {
        case sf::Keyboard::Left:
        case sf::Keyboard::Right:
            log->info() << "Stopped moving horizontally";
            player_.velocity.x = 0;
            break;
        case sf::Keyboard::Up:
        case sf::Keyboard::Down:
            log->info() << "Stopped moving vertically";
            player_.velocity.y = 0;
            break;
        }
    });

But somehow this does not seem right to me (But it wouldn't seem right to me to poll for every single possible input manually - So i think events is the things to take). Could anyone give me a hint what i am doing wrong and how to do it better?

Kind Regards


texts: Using points to unlock next scene in Unity

texts:
Below is my code and I'm a beginning game designer trying to make my first game for art school teehee! :)

I'm not sure how to unlock the next level with a scene I've already made called Rust_Room

Any ideas? :o
I also attached the error codes I'm getting!

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

public class Example
{
    HUD hud;
    int points;

    const int ScorePrefix = "Score:";
    int score;

    public void LoadLevel()
    {
        if ("Score==45")
        // load the nextlevel
        SceneManager.LoadScene(SceneManager.GetSceneByName(Rust_Room)().buildIndex + 1);

    }
}


texts: Is Java AWT suitable for 2d game rendering?

texts:
[Reposting this question from stackoverflow, as it was pointed out that it fits better here.]

I'm currently porting my 2D game engine to Java. I looked at some of the game libraries pointed at here on stackoverflow. However, the ones I looked at were rather simplistic and didn't even state if they supported things like alpha transparency, so I decided to port my C++ renderer for which I had already written out the logic.

This renderer is a pure software renderer which uses tiling to avoid needless re-rendering. I optimized its scrolling performance by creating an "offscreen buffer" a little larger than my output pane, and blitting this offscreen buffer onto my output on every frame. This way, I could avoid redrawing tiles needlessly just because I scrolled a pixel on the map.

I used Java's AWT to implement it, using a large BufferedImage for the offscreen buffer. The CPU usage is okay(around twice of what I had in C++), but there's an odd problem with continuous scrolling, where every second or so, the renderer will lag out for around 0.2 seconds.

Since there's nothing in my own code that would occur in these periods, and since the spikes disappear if I don't draw my offscreen buffer onto the main view, I can only conclude that Java is doing some internal optimization of its own. However, I'm not sure what it does, nor do I know which of my own optimizations I would have to remove to get rid of the spikes. Also, it might be that java AWT wasn't made with continuous, high FPS scrolling in mind, and that's entirely unusable for this purpose.

Is there some way for me to get rid of these spikes?


texts:
I am going through the process of rethinking my current game engine's design. And I'd like to ask about some information from other's experiences about scene graph. Before we begin, this graph is in no way shape or form going to be used directly for culling, however, it may possibly send data to the Quad-Tree system for culling. And it may limit data being sent.

The game's construction is currently using something that might be a bit of an oddball set up. It's an entity component system, but Entities are only crafted in LUA. A few of it's components are just wrappers to the C++ framework.'

Which means that the scene graph does not see entities. It just sees transforms of arbitrary objects. The benefit is that not everything in the scene needs to be an entity. However... I have to currently throw away or modify the code as it uses a structure of arrays design.

Right now, the planed re-implementation of the scene graph will do a few things.

Transform children's to their parent's fixed point.
Act as a loader for Terrain Cells and Dungeons. Cell files will simply be a branch
    of the scene graph with tags for static, and persistent objects
    (Objects that can move). The benefit of this is I can just store objects as a local to that cell in it's file, rather than having to have some sort of transform that is world dependent.
Supply the render system with a view-space
    coordinates (Camera is origin) rather than world coordinates. (I
    have no idea what DirectX's limitations are. But OpenGL is limited
    to 32bits last I checked. Float point accuracy becomes a major
    problem.)
Party Characters can possibly be split up across a large
    world. Possibly only send the cells near the camera to the render
    engine.
Entities skeletal system will be a scene graph managed by the entity it's self. But can be updated by the animation system. This is a pre-engineering design inspired by bitsquid. Unlikely to be used, but in case systems need to be reorganized, it helps.

Questions!

What should the scene graph actually handle in the world? Or would this be completely dependent on how I architect the system? From researching the ways a lot of big daddy engines handle things, everything that is a concept of matter is in the scene graph.

If I decide to use a cell based system, what owns things that can wander? Example... a player walks into some arbitrary cell (int16 X,int16 Y, in16 Z). When the scene graph calculates world coordinates, it translates into (float64 x, float64 y, float64 z).

Should the previous cell surrender ownership to the player, NPC, persistant object, or otherwise to the next cell. Or should the world just own them?

And lastly, if you do recommend this system. Could you provide me an example to an SoA method of implementing such a graph using a world Cell coordinate? The problem with SOA, is it usually implies you have a fixed type for everything. Unless, I simply keep everything as transforms. Then add extra data as hints?


texts: Best method for selecting points from a point set - path distance

texts:
having a big set of points and a polygonal path what is the best way to select a set of points that are at a certain distance or smaller from the path?
Or do I need to iterate thru all points on each segment?

More Info:

Points are randomly distributed in 2D space as well as path coords.
Path segments can vary from 10 to 100.
There can be like 100 points that needs to be selected
Incoming data is a vector of points for path, a vector of points to find the nearest one and a radius


texts:
How do I check if an iOS subscription is active?  Subscriptions are the only type of purchase available; however, there are several subscription lengths.  I have scoured the internet, but all I can find is receipt verification.

The following code seems to work for Android:

var products = storeController.products.all;
bool subscribed = products.Where(p => p.hasReceipt).Count() > 0;

(although I am not sure if it takes the subscription's expiration date into account.)

But this does not work for iOS.  How can I check to see if they have a valid iOS subscription?


texts: Real time data retrieval - database vs file system

texts:
I'm planning to develop a game in which I want to draw 3d models in real time using some given x,y,z coordinates. The coordinates will be given at an average of 30 coordinates per second. Drawing will happen maximum of 15 seconds (450 coordinate sets)

For faster retrieval what, is the most efficient way of retrieving data? Is it storing in file system (storing coordinates in a text file etc.) or storing the coordinates in a database (SQL).


texts: I am making a HD trailer for my Unity game. How do I record awesome HD shots of my game inside the Unity editor?


texts: How do I save and restore an int value with PlayerPrefs?

texts:
I am stuck on how to save the player's amount of money. When I build the game in the exe as soon as I shutdown the game my money value gets lost. I want this money to be saved. I am using the following code in UnityEngine:

using UnityEngine.UI; using System.Collections;

namespace CompleteProject
{
    public class MoneyManager : MonoBehaviour {
        public static int money; // The player's money.
        Text moneytext;          // Reference to the Text component.

        void Awake ()
        {
            // Set up the reference.
            moneytext = GetComponent <Text> ();
            money=print(PlayerPrefs.GetInt("Money"));
        }

        void Update ()
        {
            moneytext.text = "" + money;
            PlayerPrefs.SetInt ("Money", money);
        }
    }
}


texts:
I have 3 different buttons, one for each action. I want to be able to jump and walk at the same time, but there's a little problem. jumpButton doesn't work while I'm pressing leftButton or rightButton but the opposite works.

I have no idea what I'm doing wrong.

public void handleInput() {
    float x0 = (Gdx.input.getX(0) / (float)Gdx.graphics.getWidth()) * 960;
    float x1 = (Gdx.input.getX(1) / (float)Gdx.graphics.getWidth()) * 960;
    float y0 = (Gdx.input.getY(0) / (float)Gdx.graphics.getHeight()) * 640;
    float y1 = (Gdx.input.getY(1) / (float)Gdx.graphics.getHeight()) * 640;

    boolean jumpButton = (Gdx.input.isTouched(0) && x0 > 850 && x0 < 850+80 && y0 > 640-80);
    boolean leftButton = ( ((Gdx.input.isTouched(0) && x0 < 25+80) || (Gdx.input.isTouched(1) && x1 < 25+80)) && ((Gdx.input.isTouched(0) && x0 > 25) || (Gdx.input.isTouched(1) && x1 > 25)) && ((Gdx.input.isTouched(0) && y0 > 640-80) || (Gdx.input.isTouched(1) && y1 > 640-80)));
    boolean rightButton = ( ((Gdx.input.isTouched(0) && x0 < 125+80) || (Gdx.input.isTouched(1) && x1 < 125+80)) && ((Gdx.input.isTouched(0) && x0 > 125) || (Gdx.input.isTouched(1) && x1 > 125)) && ((Gdx.input.isTouched(0) && y0 > 640-80) || (Gdx.input.isTouched(1) && y1 > 640-80)));

    if (jumpButton) {
        // player jumps
    }
    if (leftButton) {
        // player walks to the left
    } else if (rightButton) {
        // player walks to the right
    } else {
        // player stops walking
    }
}


texts:
We're looking to create a split screen game using Unity that is highly reliant on audio. We would need each player to have their own headphones and use positional audio to navigate through the map.

Is it possible to output different sound (depend on each player's location) to a set of headphones? If I remember correctly, there may be a limitation in Unity and Windows where only one output device can be used. Is this true or is there some way to go about doing this?

If not, would we just have to resolve to running two instances of the game and using network play?

Thanks!


texts: Screen coordinates to a multilevel isometric world

texts:
I have an isometric world that has stuff on multiple levels, i.e. it has an XYZ coordinate system, and tiles can be stacked on each other, accumulating screen Y offset as they go. I currently have an algorithm in place that converts the screen coordinates to world XY coordinates, but it doesnt take into account that there might be e.g. a hill under the mouse and selects the tile behind it instead.

Is there a generalized form algorithm for this? I need a generalized form because all the variables are unknown (I'm writing a game engine):

Tile width (as in the width of a single tile rectangle)
Tile height (as in the height of a single tile rectangle)
Tile depth (as in how much Y offset each level contributes)

I suppose one option is run down the map with something like this (pseudo code):

p = screenToMap(screenPos)
bestMatch = null

for (x=p.x, y=p.y, z=0; x<mapWidth && y<mapHeight; x++, y++, z++) {
  b = highestPlacedBlockInPos(x, y)

  if (b.z === z) bestMatch = [x, y, z]
}

But I'm wondering if there's a better way? This seems pretty ineffective especially if you have a big map.


texts: How do I copy box2d data from one body to another?

texts:
I want to copy all Box2D-related data (position, velocity, rotation, impulse, ...) from one body to another.

This is what I've got working (with box2djsweb):

var t = body.GetTransform();
other_body.SetTransform(t);

var vel = body.GetLinearVelocity();
other_body.SetLinearVelocity(vel);

I think that covers most things, but judging by the behaviour, I've missed something. It's as if it's a frame or tick behind. Also, this isn't placing the other_body in the exact location as the the original body.

Is there a better way to do this?


texts: In Unity, how do I correctly implement the singleton pattern?

texts:
I have seen several videos and tutorials for creating singleton objects in Unity, mainly for a GameManager, that appear to use different approaches to instantiating and validating a singleton.

Is there a correct, or rather, preferred approach to this?

The two main examples I have encountered are:

First

public class GameManager
{
    private static GameManager _instance;

    public static GameManager Instance
    {
        get
        {
            if(_instance == null)
            {
                _instance = GameObject.FindObjectOfType<GameManager>();
            }

            return _instance;
        }
    }

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
}

Second

public class GameManager
{
    private static GameManager _instance;

    public static GameManager Instance
    {
        get
        {
            if(_instance == null)
            {
                instance = new GameObject("Game Manager");
                instance.AddComponent<GameManager>();
            }

            return _instance;
        }
    }

    void Awake()
    {
        _instance = this;
    }
}

The main difference I can see between the two is:

The first approach will attempt to navigate the game object stack to find an instance of the GameManager which even though this only happens (or should only happen) once seems like it could be very unoptimised as scenes grow in size during development.

Also, the first approach marks the object to not be deleted when the application changes scene, which ensures that the object is persisted between scenes. The second approach doesn't appear to adhere to this.

The second approach seems odd as in the case where the instance is null in the getter, it will create a new GameObject and assign a GameManger component to it. However, this cannot run without first having this GameManager component already attached to an object in the scene, so this is causing me some confusion.

Are there any other approaches that would be recommended, or a hybrid of the two above? There are plenty of videos and tutorials regarding singletons but they all differ so much it is hard to drawn any comparisons between the two and thus, a conclusion as to which one is the best/preferred approach.


texts:
Since Microsoft stopped developing XNA I'm wondering what will be the replacement for the XBox 720°.
I've been wondering about this. XNA was THE technologie the XBox, easy and powerfull.

So is Microsoft developing a new technologie or are they going to continue XNA, even if they've said they'd stop.


texts: Editor-only circular contour around prefab instances

texts: I have a prefab with radius setting, which programatically controls circular area with some stuff. I want instances of this prefab to display a circle with this radius in editor for convenience. Instead of radius setting I can attach circle collider to get visual border and then read its radius at runtime, but this seems code smell (I will need to programmatically remove/disable it etc), and resource waste. Are there some good practices to implement things like this?


texts: Improving the efficiency of frustum culling

texts:
I've got some code which performs frustum culling. However, this defines the "frustum" way too broadly- when I have ~10 objects on screen, the code returns 42 objects to be rendered. I've tried taking "slices" through the frustum to attempt to increase the accuracy of the technique, but it doesn't seem to have made much impact. I also significantly reduced the far plane, so that the objects are barely at the edge. Here's my code (where size is the size in screen space- the resolution of the client area of the window I'm rendering into). Any suggestions?

    auto&& size = GetDimensions();
    D3DVIEWPORT9 vp = { 0, 0, size.x, size.y, 0, 1 };
    D3DCALL(device->SetViewport(&vp));
    static const int slices = 10;
    std::vector<Object*> result;
    for(int i = 0; i < slices; i++) {
        D3DXVECTOR3 WorldSpaceFrustumPoints[8] = {
            D3DXVECTOR3(0, size.y,      static_cast<float>(i) / slices),
            D3DXVECTOR3(size.x, 0,      static_cast<float>(i) / slices),
            D3DXVECTOR3(size.x, size.y, static_cast<float>(i) / slices),
            D3DXVECTOR3(0, 0,           static_cast<float>(i) / slices),
            D3DXVECTOR3(0, 0,           static_cast<float>(i + 1) / slices),
            D3DXVECTOR3(size.x, 0,      static_cast<float>(i + 1) / slices),
            D3DXVECTOR3(size.x, size.y, static_cast<float>(i + 1) / slices),
            D3DXVECTOR3(0, size.y,      static_cast<float>(i + 1) / slices)
        };

        D3DXMATRIXA16 Identity;
        D3DXMatrixIdentity(&Identity);
        D3DXVec3UnprojectArray(
            WorldSpaceFrustumPoints,
            sizeof(D3DXVECTOR3),
            WorldSpaceFrustumPoints,
            sizeof(D3DXVECTOR3),
            &vp,
            &Projection,
            &View,
            &Identity,
            8
        );
        Math::AABB Frustum;

        auto world_begin = std::begin(WorldSpaceFrustumPoints);
        auto world_end = std::end(WorldSpaceFrustumPoints);
        auto world_initial = WorldSpaceFrustumPoints[0];
        Frustum.BottomLeftClosest.x = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.x < rhs.x ? lhs : rhs; }).x;
        Frustum.BottomLeftClosest.y = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.y < rhs.y ? lhs : rhs; }).y;
        Frustum.BottomLeftClosest.z = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.z < rhs.z ? lhs : rhs; }).z;
        Frustum.TopRightFurthest.x = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.x > rhs.x ? lhs : rhs; }).x;
        Frustum.TopRightFurthest.y = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.y > rhs.y ? lhs : rhs; }).y;
        Frustum.TopRightFurthest.z = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.z > rhs.z ? lhs : rhs; }).z;
        auto slices_result = ObjectTree.collision(Frustum);
        result.insert(result.end(), slices_result.begin(), slices_result.end());
    }
    return result;


texts: How do I make a background fill the whole screen in Libgdx?

texts:
I'm using this code to set a 800x420 image to be full screen:

public void show() {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();
    camera = new OrthographicCamera(1, h / w);
    batch = new SpriteBatch();
    texture = new Texture(Gdx.files.internal("images/splashatlas/splashatlas1.png"));
    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    TextureRegion region =
    new TextureRegion(texture, 0, 0, 800, 420);
    sprite = new Sprite(region);
    sprite.setSize(0.9f,
            0.9f * sprite.getHeight() / sprite.getWidth() );
            sprite.setOrigin(sprite.getWidth() / 2,
            sprite.getHeight() / 2);
            sprite.setPosition(-sprite.getWidth() / 2,
            -sprite.getHeight() / 2);
}

public void render(float delta) {
    Gdx.gl.glClearColor( 1f, 1f, 1f, 1f );
    Gdx.gl.glClear( GL20.GL_COLOR_BUFFER_BIT );
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    sprite.draw(batch);
    batch.end();
}

But on real device it looks like this:

I tried to setSize with different parameters:

    sprite.setSize(1.0f,
            1.0f  );

Now it's fullscreen, but it's really stretched:

What is the way to set a background to be full screen? I want it to look like this: