texts: Off-Screen Image processing with SharpDX

texts:
I need help with a image processing task... I'm using SharpDX which I am very new to. I have a device3D, device3DContext... I have a Texture2D for off-screen rendering... I have a RenderTargetView...

Here is what I cannot figure out... I need to create a Quad aligned to the target dimensions... based on a TriangleStrip... I need to load an image onto said Quad... I need to be able to apply a Pixel Shader to it...

Here is my prototype so far...

public event Action OnInitialized;

    public ImageProcessor()
    {

    }

    public void Initialize(System.Drawing.Size size)
    {
        try
        {

            var bestAdapter = DisplayAdapters.GetBestAdapter(SharpDX.Direct3D.FeatureLevel.Level_10_0);

            using (
                var device = new SharpDX.Direct3D11.Device(bestAdapter,
                    SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, bestAdapter.FeatureLevel()))
            {
                Device = device.QueryInterface<SharpDX.Direct3D11.Device1>();
            }

            using (var dxgiDevice = Device.QueryInterface<SharpDX.DXGI.Device>())
            {
                GPUDescription = dxgiDevice.Adapter.Description.Description;
            }

            DeviceContext = AddDisposable(Device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());

            var colorFormat = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            var bufferDescription = new SharpDX.Direct3D11.Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format = colorFormat,
                Height = size.Height,
                Width = size.Width,
                MipLevels = 1,
                OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage = SharpDX.Direct3D11.ResourceUsage.Default
            };

            Target = new SharpDX.Direct3D11.Texture2D(Device, bufferDescription);

            RenderTargetView = new SharpDX.Direct3D11.RenderTargetView(Device, Target);

            OnInitialized?.Invoke(this);

        }
        catch (SharpDX.SharpDXException ex)
        {

            var desc = ex.ResultCode;
        }
    }

    public System.Drawing.Image ProcessImage(string filename)
    {

        Device.ImmediateContext.ClearRenderTargetView(RenderTargetView, SharpDX.Color.Gray);

        Target = TextureLoader.CreateTexture2DFromFile(Device, filename);

        Device.ImmediateContext.Flush();

        var memoryStream = new MemoryStream();

        CopyTexture.ToImage(DeviceContext, Target, memoryStream);
        memoryStream?.Flush();

        var processedImage = System.Drawing.Image.FromStream(memoryStream);
        memoryStream?.Dispose();

        return processedImage;
    }

    private SharpDX.Direct3D11.Device1 Device;
    private SharpDX.Direct3D11.DeviceContext1 DeviceContext;

    private SharpDX.Direct3D11.Texture2D Target;
    private SharpDX.Direct3D11.RenderTargetView RenderTargetView;

    public string GPUDescription = string.Empty;

Please explain code in detail...

I've asked a similar question and someone provided a HLSL file which didn't require vertices however, I have no idea how to apply it... So I figured I'd provide the code and ask for more detailed help.


texts:
I'm a web developer, I also love games, but I really don't know anything about game development. Recently I've decided to write an outline document about an idea.
I've got a few questions to get me started, mostly I'm looking for terminology (or resources) to be able to research.

How to come up with a fair cost/gather, attack/defence/health and other ratios in a game?

1.1 is it just trial and error or there is a mathematical solution for these things?

1.2 what is the terminology for these things? what do you call them?

1.3 what area these things go into? (game designe, mechanics, etc)

1.4 what are the keywords for research and googling on these topics? (I believe 1.1 answers this too)
Is there a way to estimate development cost (in terms of time and team number)?
Is selecting a time scale for in-game by trial and error?
How to decide what requirments should be for the upgrade system? I mean, is there a solution or these things are just by tase?
what are the steps when developing a game and what to think of in each step? (I really just need resources)
most importantly, should I even worry about these things when crafting the idea? if not, which step of development should be dedicated to these things?


texts:
Suppose in a multiplayer first person shooter game that a player loses their connection. On reconnect they need to synchronize with the current game state. But while they are getting a snapshot of the game state from the server the state is changing in realtime and these need to be sent as well.

This seems like a common problem. Is there a tutorial on how to architect this in a bug free manner, and explain the gritty details of the design patterns used?


texts: Custom sampling points for anti-aliasing

texts:
I'm trying to write an anti-aliasing shader in HLSL, but I can't find any way to rasterize at a custom point. (in between pixels on the screen, but not orderly like supersampling)

Is there any way to do this completely in HLSL, or would it require external c++ code?

Currently I am creating a 2nd camera to rasterize my geometry on a screen of 1x1 at this point, and editing it from there, but it feels like this isn't the best way to do this.


texts: Understanding VAOs and adding different arrays to VAOs

texts:
I'm really confused on what you do. I can do them, however I got this problem. Say you have several squares, say 1,000 squares. Now I can make a VAO for each 1,000 squares and then do some for loop to render all of the squares. I can also use shaders to move the squares.

However, is it possible to put all 1,000 squares in one VAO.

The problem is I'm going to create a voxel game. So I need to render about 10,000 cubes. However, the game will lag a lot even if I render 200 squares how I'm currently doing it.

float points[] = {
    0.0f, 0.0f, 0.0f,
    0.3f, 0.0f, 0.0f,
    0.3f, 0.3f, 0.0f,
    0.0f, 0.0f, 0.0f,
    0.0f, 0.3f, 0.0f,
    0.3f, 0.3f, 0.0f
};

float colours[] = {
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f
};

unsigned int points_vbo = 0;
glGenBuffers (1, &points_vbo);
glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
glBufferData (GL_ARRAY_BUFFER, 18 * sizeof (float), &points, GL_STATIC_DRAW);

unsigned int colours_vbo = 0;
glGenBuffers (1, &colours_vbo);
glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
glBufferData (GL_ARRAY_BUFFER, 18 * sizeof (float), &colours, GL_STATIC_DRAW);

unsigned int vao = 0;
glGenVertexArrays (1, &vao);
glBindVertexArray (vao);
glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);
glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);

glEnableVertexAttribArray (0);
glEnableVertexAttribArray (1);

//Setup shaders
std::string vertex_shader = loadshaders("test_vs.txt");
std::string fragment_shader = loadshaders("test_fs.txt");

unsigned int vs = glCreateShader (GL_VERTEX_SHADER);
const char* str = vertex_shader.c_str ();
glShaderSource (vs, 1, &str, NULL);
glCompileShader (vs);
unsigned int fs = glCreateShader (GL_FRAGMENT_SHADER);
const char* strb = fragment_shader.c_str ();
glShaderSource (fs, 1, &strb, NULL);
glCompileShader (fs);

unsigned int shader_programme = glCreateProgram ();
glAttachShader (shader_programme, fs);
glAttachShader (shader_programme, vs);
glLinkProgram (shader_programme);

// main loop
while (!glfwWindowShouldClose(window))
{
    float ratio;
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);

    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor (0.6f, 0.6f, 0.8f, 1.0f);
    glUseProgram (shader_programme);
    glBindVertexArray (vao);
    glDrawArrays (GL_TRIANGLES, 0, 6);

    glfwSwapBuffers(window);
    glfwPollEvents();
}

So how would I say add points2[], points3[] and put them into the same VAO. How can I design my shader so I can then do transformation on the points in the arrays say translate points2[] array 4 blocks right, without effecting every other point.


texts: Separating scene generation and scene starting in Unity?

texts:
I'm working on a game, where the map is generated, and:

The map is generated in an Awake(), so when an object's Start() is called, the map should be fully initialized.
But the scene's physics world won't be updated till the next FixedUpdate.
So when Start() is called, there is a high chance, that physics operations are done in an incorrect world (like raycasting)

I tried using Physics.SyncTransforms, but it didn't solve the issue for some reason. (Why?)

My next approach was to start the objects with a delay. Precisely: after a FixedUpdate.

So I started a Coroutine in the Start() method, which waits for a FixedUpdate, then starts the object.
But this caused that for example: ObjectA's Update() is called before ObjectB's Start coroutine finishes.

How could I achieve that scenes won't be started until the scene is fully initialized?

Is there a way to tell Unity to call every Start() i.e. 1 frame later? Or how else could I fix this? What is the best solution?


texts: Exporting steps/actions with a 3D Studio Max plugin

texts:
I'm trying to figure out how this plugin works behind the scenes. Do you know if there is any 3ds-max API function (maxscript/c++/python) which allows to record the action history somehow?

You could claim there is the max-recorder... in fact, this one does "almost" what I want... but the idea would be writing a plugin to export the max actions to my own custom format.

Example:

1) I create a cube with certain parameters
2) I select it
3) I apply a modifier with certain parameters

Imaginary output:

output = [
   {"action":"create_cube", "params":{"name":"cube1", "size":10, "tess_x":2, "tess_y":3, ...},
   {"action":"select_mesh", "params":{"name":"select_mesh1" "selection": "cube1", ...},
   {"action":"subdivide", "params": {"name":"subdivide1", "type": "catmull-clark", ...},
   ...
]

Thanks in advance.

PS: I haven't been able to contact that author's plugin to get some info about it, otherwise I wouldn't be asking ;-)


texts: Cocos2d Vertical Doodle-Jump Like Scrolling

texts:
Good afternoon,

For the past few days I've been making a game very similar to DoodleJump in the sense that it involves a main character, things to jump on, certain powerups and some monsters.
I've pretty much laid the foundation for everything I need except for one thing. And no, I'm not going to release this game on the app store for publicity, nor do I plan on trying to claiming it as my own game, since the entire game borrows from DoodleJump. I am creating this game as a practice project for myself.

I need some way to implement the "infinite" vertical scrolling that appears in DoodleJump.
I've tried several things and searched through many forums and discussion pages, but I can't seem to find one.

Here's some of things I've tried:

- (void) followPlayer
{
   static CGSize winSize = [[CCDirector sharedDirector]winSize];
   static float fixedPos = winSize.height * .25;
   CCLOG(@"Fixed pos: %f",fixedPos);
   float newY = fixedPos - mainPlayer.position.y;    // mainPlayer
                                                  is a custom object I created
   newY = MIN(newY,fixedPos);
   newY = MAX(newY,-maxHeight - fixedPos); // maxHeight is a float
                                             that keeps track of how high in (y)
                                             coordinates the map is. i.e
                                             every time I add something to the map,
                                             I increment this counter to account
                                             for the new object's height.

   CGPoint pos = ccp(self.position.x,newY);
   [self setPosition:pos];

}

That method gets called in my update method, so it's supposed to position the screen to follow the character, however it doesn't work as expected. The screen shifts slightly up even when the character hasn't passed the 25% margin that I defined, some static bodies that I created with Box2D also get all messed up.

Is there any other thing I can implement to achieve the "infinite" vertical scroll? I really hit a brick wall on this one, any suggestions would be greatly appreciated.

Edit
  Here's the code for the failing scrolling background.

This is my BackgroundLayer class that contains the background images:

- (id) init
{
   self = [super init];
   if(self)
   {

     back1 = [CCSprite spriteWithFile:@"Background.png"];
     back1.anchorPoint = ccp(0,0);
     [back1 setPosition:ccp(0,0)];

     [self addChild:back1];
     [self scheduleUpdate];
   }

   return self;
}
- (void) update:(ccTime) dt
{

    CGPoint b1 = [back1 position];
    b1 = [[self parent] convertToNodeSpace:b1];
    if(b1.y < 0)
    {
        back1.position = ccp(0,back1.contentSize.height);
    }

}

This class is then being added as a child in my HelloWorldLayer class as the variable layer, which gets scrolled as the player moves up.


texts: Android OpenGL ES RENDERMODE_WHEN_DIRTY implementation

texts:
I am trying to understand RENDERMODE_WHEN_DIRTY so that I could save battery life wherever possible.. I made this sample application so that GlSurfaceView is updated with random color only when the random number temp is greater than 50... If the value of temp is less than 50, I want it to retain the last random color.. But in this code sample, it is not retaining it but making the screen go black forever!

Basically I want to know if my implementation of RENDERMODE_WHEN_DIRTY correct...

package com.blob.blob;

import java.util.Random;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.util.Log;

public class OpenGLActivity extends Activity implements Renderer
{
    GLSurfaceView glView;
    Random rand ;
    @Override
    public void onCreate(Bundle s)
    {
        super.onCreate(s);
        glView = new GLSurfaceView(this);
        glView.setRenderer(this);
        glView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        rand = new Random();
        setContentView(glView);

    }

    public void onDrawFrame(GL10 gl)
    {
        int temp = rand.nextInt(100);

        if(temp > 50)
        {
        glView.requestRender();

        gl.glClearColor(rand.nextFloat(), rand.nextFloat(), rand.nextFloat(), 1);
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        }

    }

    public void onSurfaceChanged(GL10 gl, int width, int height) {

        Log.d("OpenglTest", "Surface Changed");
    }

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        Log.d("OpenglTest", "Surface Created");
    }

    public void onPause()
    {

        super.onPause();
        glView.onPause();

    }

    public void onResume()
    {
        super.onResume();
        glView.onResume();
    }
}


texts:
I am making an classic 2D arcade ball game. There will be 100 levels in this game. And after the 80th level passing the level by doing some arcade stuff will be very difficult.

For example level 100 will be the most difficult level and if I can't pass this level with manual testing (I am not very skillful), how can I know without manual testing if the 100th level can be passed?

(I don't want to make an impossible level. I just want to make a very difficult level.)


texts:
I am sure that inventoryItem.Name contains "Wood" cause i see it when i add a breakpoint. Still i get nothing in the game. Just empty buttons.

void DrawInventoryContent (int id)
    {
            var buttonIndex = 0;
            var x = 0;
            var y = 0;

            foreach (var item in inventoryItems) {
                    //create position rectangel for button
                    var startMargin = buttonMargin;
                    var leftStartPosition = startMargin + buttonMargin * x + buttonWidth * x;
                    var topStartPosition = startMargin + buttonMargin * y + buttonHeight * y;
                    var buttonRectangel = new Rect (leftStartPosition, topStartPosition, buttonWidth, buttonHeight);

                    //Get inventoryiten by index
                    var inventoryItem = inventoryItems [buttonIndex];
                    var name = inventoryItem.Name;

                    //Create and place buttin
                    GUI.Button (buttonRectangel, name);

                    // check if this button is at end of row and change to next row
                    if (x == buttonsPerRow - 1) {
                            x = 0;
                            y++;
                    } else {
                            x++;
                    }
                    //go to next item
                    buttonIndex ++;

            }
    }


texts: Any way to load/execute scripts (game-logic) included in a post-release DLC (Unity3D AssetBundles) on iOS since it seems its not allowed?

texts:
We are making a game where players will be granted access to new levels every week and these new levels will probably be downloaded from our server as Unity Asset Bundles
The only issue is, as mentioned here , ios and other app stores dont allow loading/executing of scripts this way even if they allow you to load these newer asset bundles without doing the full update cycle. So really we need to know how game-logic scripts, etc can be executed for the new levels that are going to be released via Asset Bundles and downloaded from our server. Our server will be authoritative btw. I am sure there is a way since big game publishers are able to do post-release DLC and really, thats what we are after too - Just more regularly, whilst being in-line with app store regulations.
Our usual workflow until now was just publish and then release a big update months down the line. Not every week.


texts:
I have a Player with a capsule collider on him and i have various objects in the scene. Most of the objects have either mesh collider or box collider enabled.
When i move my player and the player collides with any object, my player just starts flying into space, literally.
Any way to fix this?

Thanks in Advance.

The code i have on my player is this:

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour {
Animator anim;
Rigidbody rbody;
float inputH;
float inputV;
int Life=20;
bool Dead=false;
public float sensitivity=10f;
void Start () {
    anim = GetComponent<Animator> ();
    rbody = GetComponent<Rigidbody> ();
}
void Update () {
    if (Dead == false) {
        inputH = Input.GetAxis ("Horizontal") * 50f;
        inputV = Input.GetAxis ("Vertical") * 20f;
        anim.SetFloat ("inputH", inputH);
        anim.SetFloat ("inputV", inputV);
        float moveX = inputV  * Time.deltaTime;
        float moveZ = inputH * 0.5f * Time.deltaTime;
        this.transform.position += this.transform.forward * moveX;
        this.transform.position += this.transform.right * moveZ;
        transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivity, 0);
    }
    if (Input.GetKey (KeyCode.Z))
        Life--;
    if (Life == 0)
        Dead = true;
    anim.SetBool("Dead",Dead);
}
}


texts:
I'm looking for a fast opensource C++ math-library for my game engine
with the following features:

fast (sse?)
vectors
matrices
quaternions

suitable for both opengl and directx


texts: Why rendered objects to cubemap are larger than they should be?

texts:
I am trying to render a scene to a cubemap, so I can later use it as environment map for another object. The object I want to use the environment map with is a surface, I am trying to render water. But I have an issue, when the refraction index is set to 1.0 (air), the skybox is shown correctly, however the other object is not.

The circled area is where the cube made out of air is, in these images:

But when I position my camera so it includes a part of the stone platform, the stone platform appears much more larger than it should be:

I render to cubemap as follows:

glm::mat4 translateInfoMat = x.model - glm::mat4(glm::mat3(x.model));
glm::vec3 position = glm::vec3(translateInfoMat[3][0], translateInfoMat[3][1], translateInfoMat[3][2]);//gets the view position of the cubemap from the object's model matrix.

glm::mat4 _projection = glm::perspective(glm::radians(90.0f), 1.f, 0.1f, 2000.0f);

for(int j = 0; j < 6; j++)// for each face it renders the scene
{
    envMap.bindRenderToFace(j); //sets the current face to draw to.
    glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glm::mat4 _view = glm::lookAt(position, position + targets[j], ups[j]);

    //renders skybox
    glDepthMask(GL_FALSE);
    if(skybox != NULL)
    {
        skybox->setVP(_projection * glm::mat4(glm::mat3(_view)));
        skybox->draw(&skyboxShader);
    }
    glDepthMask(GL_TRUE);

    for(int i = 0; i < renderQueue.size(); i++)//renders the objects that doesn't need environment map (the stone platform)
    {
        RenderableElement object = renderQueue[i];
        if(!y.renderInfo.m_needsEnvironmentMap)
        {
            lighting.SetMVP(_projection * _view  * y.model);
            lighting.SetModel( object.model);
            lighting.SetViewPos(viewPos);

            lighting.Use();

            object.mesh->Draw(lighting.GetShader());
        }
    }
}

And the shader that does the refraction is:

#version 330 core

in vec3 FragPos; //the position of the current fragment in world space
in vec3 Normal; //normal in world space

out vec4 FragColor;

uniform vec3 viewPos;
uniform samplerCube skybox;

vec3 refraction(vec3 normal, vec3 viewPos, vec3 fragPos, float n1, float n2)
{
    vec3 i = normalize(fragPos - viewPos);
    vec3 r = refract(i, normalize(normal), n1 / n2);

    return texture(skybox, normalize(r)).rgb;
}

void main()
{
    vec3 normal;

    normal = normalize(Normal);

    vec4 refr = vec4(refraction(normal, viewPos, FragPos, 1.0, 1.0), 1.0);

    FragColor = refr;
}

I have verified my code with multiple sources, and they are doing approximately the same way as I have done. The data fed to the shader is correct (normals, vertex position, model matrix, view position, etc.).


texts: Fixed timestep, how to determine how far back other clients are simulated

texts:
I'm working on networking code for a social MMO (very low-intensity compared to an FPS) and have a question about fixed timestep.

This answer does a good job of explaining the forward-dating part of utilizing a fixed timestep, but doesn't seem to have the whole picture.
If the forward-dating was meant to account for the packet getting all the way through the server to the other clients, wouldn't it have to either take into account the latency of the most latent client in order to arrive in time, or deal with it being late? I assume this is where the "simulate other clients as being a few ticks behind" concept comes in.

My question is: how is this back-dating offset calculated? Is it a single number for all other clients, or should it be variable through the server sending each client's latency? What goes into the calculation?

I would assume that the starting point is any delay caused by differences in tick rate between the game tick and networking tick (e.g. game is 60 ticks/s, network is 20 and both are in phase, you need to push clients back at least 2 ticks to let the server's network re-tick.) Is this understanding accurate?


texts: Entity-Component-System and 2D map with tiles : how to do it?

texts:
I have a question : I'm currently programming a roguelike game (with tiles) using the ECS programming paradigm, and I'm struggling with how to implement the map.

At first, I made every terrain square an entity (with a screenPosition and a sprite components), but that quickly lead to performance issues (a 100x100 map is already 10k entities).

So now, I want to treat the whole map of a level as a single entity, but I'm unsure on how to do it. Should I make a map component, that will store every terrain properties? That seems "bad" to me. Is there a better way?

Thanks

Edit :

My implementation is something like this :

Each entity is a struct that store a list of pair of component_id (an int) and component_handle (an int).
Components are struct
an EntityManagerSystem store all the entities in a vector, and all the components, each kind in its own vector. Each vector is public, the id of each entity is its vector index, and the component handle is the component index too
a RenderSystem that iter over the entity vector from EntityManagerSystem, and draw the ones that have the corresponding components
an EngineSystem store pointers to all the Systems and call them sequentially to update : it's the "main" class

In RenderSystem, it's this loop the culprit :

em is the entityManager and CT_HASH is a compile time hash.

for (std::vector<GameObject>::iterator it = em->entities.begin(); it != em->entities.end(); ++it)
{
    if (it->HasComponent(CT_HASH("ScreenPosition")) && it->HasComponent(CT_HASH("Sprites")))
    {
        ScreenPosition pos = em->screenPosition[it->GetComponent(CT_HASH("ScreenPosition"))];
        if (0 <= pos.x && pos.x < xSize && 0 <= pos.y && pos.y < ySize)
        {
            Sprites sprites = em->sprites[it->GetComponent(CT_HASH("Sprites"))];
            for (int z = 0; z < 10; z++)
            {
                if (sprites.sprites[z] != 0)
                {
                    spriteMap[pos.x][pos.y][z] = sprites.sprites[z];
                }
            }
        }
    }
}

It takes around 300ms for a 100x100 map with only the terrain entities


texts: Unity 5 C# - onClick.AddListener in a foreach loop using lambda expressions

texts:
I'm trying to dynamically create Unity 5 UI buttons that each set a global variable decision_id to a different value when clicked.

The problem I'm having with this implementation is that they all set decision_id to the exact same value right now. That value being the last one in my foreach loop.

Here's my code:

IEnumerator make_decision(XmlNode options_node) {
    // reset decision_id
    decision_id = "nothing";

    // spawn a button for each option_node in options_node
    int i = 1;
    var new_option_1 = Instantiate(option_1);
    var new_option_2 = Instantiate(option_2);
    var new_option_3 = Instantiate(option_3);
    var new_option_4 = Instantiate(option_4);
    foreach (XmlNode option_node in options_node) {
        XmlNode temp_option_node = option_node;
        string option_id = temp_option_node.Attributes["id"].Value;
        Debug.Log(option_id);
        switch (i) {
            case 1:
                new_option_1.GetComponentsInChildren<Text>()[0].text = option_node.InnerText;
                new_option_1.GetComponent<Button>().onClick.AddListener(() => set_decision_id(option_id));
                new_option_1.transform.SetParent(canvas.transform, false);
                break;
            case 2:
                new_option_2.GetComponentsInChildren<Text>()[0].text = option_node.InnerText;
                new_option_2.GetComponent<Button>().onClick.AddListener(() => set_decision_id(option_id));
                new_option_2.transform.SetParent(canvas.transform, false);
                break;
            case 3:
                new_option_3.GetComponentsInChildren<Text>()[0].text = option_node.InnerText;
                new_option_3.GetComponent<Button>().onClick.AddListener(() => set_decision_id(option_id));
                new_option_3.transform.SetParent(canvas.transform, false);
                break;
            case 4:
                new_option_4.GetComponentsInChildren<Text>()[0].text = option_node.InnerText;
                new_option_4.GetComponent<Button>().onClick.AddListener(() => set_decision_id(option_id));
                new_option_4.transform.SetParent(canvas.transform, false);
                break;
            default:
                Debug.Log("Too many option nodes! Should only be four per options section");
                break;
        }
        i++;
    }

    while (decision_id == "nothing") {
        yield return new WaitForSeconds(.5f);
        // the button will change decision_id for us eventually
        // decision_id = "monarchy";
    }

    // despawn each button spawned above
    Destroy(new_option_1);
    Destroy(new_option_2);
    Destroy(new_option_3);
    Destroy(new_option_4);

}

I've searched this issue and have found lots of talk about the lambda's capturing instances instead of values... but I've already gone out of my way to prevent this by capturing both the XmlNode itself AND the id string in local variables.

Is there something super obvious that I'm missing here?


texts:
How to set up an architecture and a strategy allowing the persistence of the data of a MUD in a relational database?

Type of game:

My question relates to the design of a Multi User Dungeon (MUD).

A MUD is a textual online game, considered today as the ancestor of the MMORPG. Players create characters and then control them in a completely text-based world using commands. For example, they can move from room to room, kill monsters, collect items, equip themselves with armour and weapons, solve quests, etc.

From a technical point of view, it is simply a server written in C++. Players connect using MUD clients or directly via the telnet protocol.

My objective:

I would like to ensure the persistence of the game using a relational database.

For performance purposes, I do not intend to load and save my data from the database in real time.

I plan to:

load all my data in memory at the launch of the MUD
save only objects that will be modified during runtime at regular intervals of time (every minute for example)

If possible, I would obviously like the code that ensures the persistence of the data to be completely independent of the game data.

My problem:

I have a hard time knowing which architecture to set up.

For instance, I do not know how to manage the dependencies of the objects between them. For example:

an object of type Character has a pointer to an object of type Room
this object of type Room itself has a list of pointers of Objects placed on the ground
these Objects themselves have a pointer to their Prototype (a prototype corresponds to the model of the object)
etc.

How do I do to load all these dependencies properly? I could obviously hack a code that does it. However, I do not see how to do it cleanly. Is there a relatively simple way to do it, without coding an entire ORM for that?

All the examples that I find on the internet mention the different Design Patterns put in place by the ORMs. It looks complex. It must be a lot of code to write!

Or they give answers that do not seem satisfactory. For example:

“You may have objects that point to too many other objects for them to be loaded immediately. Sometimes linked objects will link to other objects further increasing the amount of data to be loaded if you want to load all dependencies at once. It may even happen that you encounter endless reference loops leading to stack overflows or script timeouts.
This means that most of the time we need to make a judgment where to cut off the dependency chains.”

Source: https://pkp.sfu.ca/wiki/index.php/Data_Access_Objects_(DAO)#One-to-many_or_many-to-many_relations_of_independent_objects

I don’t want to cut the dependency chains. I just want my entire object graph. Not less. Not more!

The problem I encounter, however, seems relatively basic. It had to be solved millions of times. However, I can not find examples or solutions that are clear and relatively simple.

My first approach:

I could maybe:

load all my objects without any dependency
once all my objects are loaded and accessible in memory, some methods might have the task of solving all these dependencies and recreating all the links between the objects

In this case, does that mean that I will have to store the Primary Keys of the different objects directly in the objects? It would break the total independence of my game objects and the way I persist my data.

My question would be:

In the case of an online game and since my different game objects will be strongly linked to each other, what would be a possible strategy and architecture allowing the saving and the loading of these data in a relational database, while managing the dependencies of the objects between them?

How do people usually solve this problem?


texts: Implementing a sine using a bezier curve

texts:
I'm developing a 2D game using Cocos2d-x.
Is possible to use CCBezierTo to parameterize a sine function?


texts:
Hello Everyone,
               I want to create a game using OPEN GL to learn basics of the game development. I know C++ and OOPS and can manage the coding. I have tried using the free engines on the market like Unreal Engine, Unity and Game Maker. Unreal Engine in particular doesn't work well on my System due to it's higher requirements. Even all other engines have some kind of abstraction to themselves. I have time to spare. So, please suggest me a starting point to start developing using OPEN GL and also the math required to create them. All I want to do is learn it thoroughly at the lower level.
Thanks in advance


texts: How to start simple game development with Unity 5

texts:
I want to start developing games with Unity because it's easy to learn, but I don't know where to start.

My questions are:
- Which preparations should I make for a game?
- Are there any tips and tricks for efficient work?
- Do I need special equipment?

Thank you for your response!


texts:
so I am using Guide.BeginShowKeyboardInput to get the user to enter their username. I would like this to be limited to 20 characters, and it seems to break expected behaviour to let them input whatever they like and trim it later - so how would I go about limiting what they can input in the text box itself? I have the following code:

public string GetKeyboardInput(string title, string description, string defaultText, int maxLength)
    {
        if (input.CheckCancel())
        {
            useKeyboardResult = false;
            KeyboardResult = null;
        }

        if (KeyboardResult == null && !Guide.IsVisible)
        {
            KeyboardResult = Guide.BeginShowKeyboardInput(PlayerIndex.One, title,
                                                          description, defaultText, null, null);
            useKeyboardResult = true;
        }
        else if (KeyboardResult != null && KeyboardResult.IsCompleted)
        {
            string result = Guide.EndShowKeyboardInput(KeyboardResult);
            KeyboardResult = null;
            if (result == null)
            {
                useKeyboardResult = false;
                return null;
            }

            if (useKeyboardResult)
            {
                KeyboardResult = null;
                return result;
            }
        }
        else //the user is still entering inputs
        {

        }

        return null;
    }

I assume the code I need would go in that final, empty else{} block, but I can't see any way to do this. Does anyone know how?


texts:
If you define a constant buffer in a shader, for example

cbuffer test : register(c2)
{
    float4x4 data;
}

But never actually use the data in the shader, does that incur any runtime cost at all?
It's convenient for me to do this but not at the cost of slowing runtime performance at all. When I time it I don't see any difference...


texts: problem adding bumpmap to textured gluSphere in JOGL

texts:
I currently have one texture on a gluSphere that represents the Earth being displayed perfectly, but having trouble figuring out how to implement a bumpmap as well.
The bumpmap resides in "res/planet/earth/earthbump1k.jpg".Here is the code I have for the regular texture:

    gl.glTranslatef(xPath, 0, yPath + zPos);
    gl.glColor3f(1.0f, 1.0f, 1.0f); // base color for earth

    earthGluSphere = glu.gluNewQuadric();

    colorTexture.enable(); // enable texture
    colorTexture.bind(); // bind texture

    // draw sphere...
    glu.gluDeleteQuadric(earthGluSphere);
    colorTexture.disable();

// texturing
public void loadPlanetTexture(GL2 gl)
{
    InputStream colorMap = null;

    try
    {
        colorMap = new FileInputStream("res/planet/earth/earthmap1k.jpg");
        TextureData data = TextureIO.newTextureData(colorMap, false, null);
        colorTexture = TextureIO.newTexture(data);
        colorTexture.getImageTexCoords();
        colorTexture.setTexParameteri(GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
        colorTexture.setTexParameteri(GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_NEAREST);
        colorMap.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
        System.exit(1);
    }
    // Set material properties
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_NEAREST);

    colorTexture.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S);
    colorTexture.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T);
}

How would I add the bumpmap as well to the same gluSphere?


texts: Mixing DirectX headers with C mod project not working

texts:
I'm trying to add a DirectX 11 renderer (not sure if that is even doable in a "simple" manner) to the Return To Castle Wolfenstein source code and I'm having some problems. I have a rendering class in a header that I included in the project, and whenever I include it in one of the RTCW files I get this error:

1>c:\program files (x86)\windows kits\8.1\include\um\directxmath.h(17): fatal error C1189: #error:  DirectX Math requires C++

Now I am wondering what would be a way to use DirectX math functions/classes (and all DirectX classes actually) in a C project such as the RTCW code? Is it possible to change the entire project settings so it compiles as C++? I am using Visual Studio 2017.

This is my renderer class declaration in XD3D.h header:

#include <d3d11.h>
#include <DirectXMath.h>
#include "XGeomObject.h"
#include "XCamera.h"

using namespace DirectX;

#define GPA(d3dModule, func) GetProcAddress(d3dModule, func)

class XD3DRenderer
{
protected:
    HMODULE                     m_XD3DModule;
    ID3D11Device*               m_pD3DDevice;
    ID3D11DeviceContext*        m_pDeviceContext;
    IDXGISwapChain*             m_pSwapChain;
    ID3D11RenderTargetView*     m_pRenderTargetView;
    ID3D11Texture2D*            m_pBackBuffer;
    ID3D11Texture2D*            m_pDepthStencilBuffer;
    ID3D11DepthStencilState*    m_pDepthStencilState;
    ID3D11DepthStencilState*    m_pDisabledDepthStencilState;
    ID3D11RasterizerState*      m_pRasterState;
    ID3D11DepthStencilView*     m_pDepthStencilView;

    HWND                        m_wnd;
    int                         m_screenWidth, m_screenHeight;
    bool                        m_fullScreen;
    D3DXMATRIX                  m_world, m_view, m_proj;
    bool                        m_lightMapsOn;

public:
    XD3DRenderer();
    XD3DRenderer(HWND wnd, int screenwidth, int screenheight,bool fullscreen);
    ~XD3DRenderer();

    ID3D11Device* GetD3DDevice() { return m_pD3DDevice; }
    ID3D11DeviceContext* GetDeviceContext() { return m_pDeviceContext; }

    bool LoadDriver();
    bool CreateD3DDevice(HWND wnd, int screenwidth, int screenheight, bool fullscreen );
    bool CreateRenderTargetView();
    bool CreateDepthBuffer();
    bool CreateDepthStencilView();
    bool CreateDisabledDepthStencilState();

    bool Setup();
    bool ClearScene(const D3DXCOLOR& col);
    bool Render(XGeomObject*, XCamera*);
    bool ShowScene();
    void TurnOnZBuffer();
    void TurnOffZBuffer();
};

And I include it in the C project in the RTCW win_glimp.c file like this:

#include <assert.h>
#include "../renderer/tr_local.h"
#include "../qcommon/qcommon.h"
#include "resource.h"
#include "glw_win.h"
#include "win_local.h"

#include "../renderer/XD3D.h"

extern void WG_CheckHardwareGamma( void );
extern void WG_RestoreGamma( void );

... rest of win_glimp.c file omitted.


texts:
So I am using Kinect with Unity.

With the Kinect, we detect a hand gesture and when it is active we draw a line on the screen that follows where ever the hand is going. Every update the location is stored as the newest (and last) point in a line. However the lines can often look very choppy.

Here is a general picture that shows what I want to achieve:

With the red being the original line, and the purple being the new smoothed line. If the user suddenly stops and turns direction, we think we want it to not exactly do that but instead have a rapid turn or a loop.

My current solution is using Cubic Bezier, and only using points that are X distance away from each other (with Y points being placed between the two points using Cubic Bezier). However there are two problems with this, amongst others:

1) It often doesn't preserve the curves to the distance outwards the user drew them, for example if the user suddenly stop a line and reverse the direction there is a pretty good chance the line won't extend to point where the user reversed the direction.

2) There is also a chance that the selected "good" point is actually a "bad" random jump point.

So I've thought about other solutions. One including limiting the max angle between points (with 0 degrees being a straight line). However if the point has an angle beyond the limit the math behind lowering the angle while still following the drawn line as best possible seems complicated. But maybe it's not. Either way I'm not sure what to do and looking for help.

Keep in mind this needs to be done in real time as the user is drawing the line.


texts: Can you recommend a 2D game engine compatible with Windows Phone?

texts: I'm curious what people are using to develop games for the Windows Phone (or XNA in general). I have come across a few engines but for the most part they don't seem to be actively maintained. If you are using an engine which you think does the job well please recommend it below.


texts: How to make the background of an OpenGL object transparent?

texts:
It sounds so simple but i didn't get it to work.

The Background of my FrameLayout where i add the GLSurfaceView in is colored blue but there is only black.

So here is my method to initiate the Surface...GL..

private void initGL(){

    ourSurfaceView = new GLSurfaceView(this);   // GLSurfaceView Objekt erstellen
    ourSurfaceView.setEGLConfigChooser(new MultisampleConfigChooser());
    ourSurfaceView.setRenderer(new GLRendererTamago());

    //In every help i read that it shoud help to use the following two commands... but they did nothing for me.
    ourSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
    ourSurfaceView.setZOrderOnTop(true);

    FrameLayout tama_layout = (FrameLayout)findViewById(R.id.LayoutTama);
    tama_layout.addView(ourSurfaceView, 0);

}

Someone have any idea?

edit: added the code from my renderer

@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {

    gl.glDisable(GL10.GL_DITHER);
    gl.glDisable(GL10.GL_DEPTH_TEST);
    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
    gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
//  gl.glClearDepthf(1f);
//  gl.glClearColor(0,0,0,0);
}

@Override
public void onDrawFrame(GL10 gl) {

    gl.glDisable(GL10.GL_DITHER);
    gl.glDisable(GL10.GL_DEPTH_TEST);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();
    GLU.gluLookAt(gl, 0, 0, -5, 0, 0, 0, 0, 2, 0);

    body.draw(gl);
    eyes.draw(gl);
    mouth.draw(gl);
}

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {

    gl.glViewport(0, 0, width, height);
    float ratio = (float)width / height;
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glLoadIdentity();
    gl.glFrustumf(-ratio, ratio, -1, 1, 1, 20);
}


texts: How can I correctly manage different utility classes between engine and libraries?

texts:
I'm currently building an engine over SFML and Box2D.

The problem is that each of these use different types for things like Vector2, etc.

So to the question: is it a good idea to replace Box2D and SFML vectors with my own vector class (which is one of my better implementations)? My idea then was to have a separate .lib with all my classes that should be shared between all the projects in the solution.


texts:
I'm currently developing a small game project on unity (with purpose of learning C#) where each player controls a base and can build buildings, do research, build units, pretty much the basis.

I arrived where the each player may send their army of different sizes to attack the other player's base. Each army can be composed of three different unit types, being Infantry, Archers and Cavalry. They work as a kind of rock-paper-scissors, meaning infantry beats cavalry given equal resources (horses cost more than warriors, so 1 on 1, cavalry still wins), cavalry beats archers and finally, archers beats infantry given a long distance.

Every unit has different stats, health, damage, armor and range (mouvement speed exists but I do not want to consider it in battle).

I want the battle to be split in rounds and that it is not because you have less soldiers than the other player that you should loose. What would be an interesting way of solving the battle taking account of all those variables ?

Sort of solution I have is to give each player some decisions as to what would he do first (either archers attack first, cavalry waits for flanks, etc.) but nit seems too complicated and I still don't know how each parameter should be calculated. Should luck be included too ?

Thanks,
luisarcher.

EDIT

After comments, here is my question more clearly. What would be the best way to simulate a battle of two armies composed of those units (with their weaknesses and strengths) where both armies would loose troops in X amount of rounds ?

I want the results to evolve with time so the players can react to it (either retreat, or maybe small commands). I'm not looking for a piece of code, but more of a guideline of how should I use every attribute of each unit (health, damage, armor and range).

EDIT2

By best, I mean an interesting resolution where each unit feels unique to be built and where players won't feel forced to build only 1 kind of units since it has the most cost effective hp/damage per amount of resource spent. I'm thinking of something like all those web-based strategy games like Grepolis, Tribal Wars, oGame, etc.


texts: Can I take pictures of things I own and use them in a game as art assets or is that an IP violation?

texts: For example what if I take a picture of a Tonka truck, can I use that as an art asset?  What if the toy is more generic?


texts: A pattern for a contextual InputState in a Game State Management architecture

texts:
Context of the question :

When developing a game using Game State Management I came across a problematic when it came to handling user input : I want my game to retrieve user input a single way, but to handle it in a completely different way, depending on the context.

For example, the [Up] key will always mean "Menu Up" when you're in a menu, but if you're in the game, it might do different things, depending on the key bindings. Another difference would be, for example, that in a menu, a .5sec KeyDown on a key should be interpreted as a single command, but when you're in game, a .5sec KeyDown should often be seen as a .5sec movement / burst / charge shot / etc...

Then way I though about to achieve this result is the following :

Have an InputState class that keeps the current and previous Keyboard/Gamepad input states, just like the usual InputState class. Have this InputState class implement all the methods I would need in all the different contexts.
Create an Interface per context. For example, IMenuInputState, IGameInputState, ICutsceneInputState, etc. These interfaces would only contain the method definitions related to the context.
Have the InputState implement all the I[...]InputState interfaces. If two or more context need the same method, the same implementation would be used.
In the ScreenManager's Update method, the InputState would be Updated, but depending on which screen must handle the InputState, a different I[...]InputState would be sent. Even though the screen could access the other methods by casting the interface, only the contextual methods would directly be usable.

My question is the following : Is my idea a proper / common way of handling this issue?

If it is, could you tell me the name of that "pattern" or direct me to some online resources so I can read on that and avoid the known pitfalls. If it's not, how would you suggest I handle the problem?

Note: I know this question is borderline since the answer is partially subjective but I'd appreciate some help on this issue since I think it's a critical decision in my project.


texts:
Possible Duplicate:
  Mods for Minecraft Server - how does it work?

I have made some minecraft client mods, but i've started a server a mounth ago and i want to make a mod for it, but i cant find any tutorial on the internet. How can then the other guys making those mods for minecraft server know how they are going to do? Do they try forward as i tryed or are they doing something else. I would be glad if someone could tell me how to do or find tutorials for me, couse I have tryed to find them in nearly a week of searching. But i guess im searching at the wrong spot of internet, what do i know :o


texts:
I'm trying to wrap my head around how batching is done in a 2D sprite-based game.  My understanding is I'd get the vertices that represent each sprite I want to draw and stuff them all into a single mesh.  That way I'd only need a single draw call to render everything.

Does this apply when the sprites I render are different between frames, or when some sprites are moving?  Because it sounds like I'd then have to recreate my batch mesh each frame, using either glDrawArrays/glDrawElements or a streaming VBO I assume.  Does this sound correct?


texts: How signals work when Node2D is queue_freed?

texts:
Consider this setup:
* KinematicBody2D (Player)
|- Sprite (icon.png)
|- VisibilityNotifier2D

With Player.gd:
class_name Player extends KinematicBody2D
signal unvisible

onready var visibility_notifier :VisibilityNotifier2D = $VisibilityNotifier2D

func _ready() -> void:
    visibility_notifier.connect("screen_exited", self, "__on_screen_exited")

func __on_screen_exited() -> void:
    emit_signal("unvisible")

Now I have a template Level.gd:
* Node2D (Level)
|- Player

extends Node2D

onready var player :Player = $Player

export var debug_no_enemy  = false
export var debug_no_player = true

func _ready() -> void:
    player.connect("unvisible", self, "_reset_level")
    if debug_no_player:
        player.queue_free()

func _reset_level() -> void:
    print("reset")
    get_tree().reload_current_scene()

The print statement proves that this setup make a kind of infinite loop of reset because the signal screen_exited is still emited when the player is queue_free.
Is it expected?

I am even more surprised with this modified version which produces the same thing:
func _ready() -> void:
    if debug_no_player:
        player.queue_free()
    player.connect("unvisible", self, "_reset_level")


texts: Unity Co-ordinate system to latitude longitude conversion floating point precision lost

texts:
I am using a Github script (Unity GPS Convertor) to convert unity co-ordinate system x,z into latitude and longitude. It is actually working fine but the problem is, when I go farther from the origin (0,0,0) my conversion is no more accurate. I deeply try to study this topic and found a valuable blog about unity coordinate limitation which states that

  Floating Point Accuracy Unity allows you to place objects anywhere
  within the limitations of the float-based coordinate system. The
  limitation for the X, Y and Z Position Transform is 7 significant
  digits, with a decimal place anywhere within those 7 digits; in effect
  you could place an object at 12345.67 or 12.34567, for just two
  examples.

  With this system, the further away from the origin (0.000000 -
  absolute zero) you get, the more floating-point precision you lose.
  For example, accepting that one unit (1u) equals one meter (1m), an
  object at 1.234567 has a floating point accuracy to 6 decimal places
  (a micrometer), while an object at 76543.21 can only have two decimal
  places (a centimeter), and is thus less accurate.

It means that if I put any object at 10000 position of x then, the floating point accuracy will only be 2 decimal places? My Current environment is very large and even one object position is at 90000 of x coordinate in unity position. So my question is that how can I convert the lat-long correctly keeping in mind this floating point accuracy problem. The Unity GPS Convertor library is fine but it based on float.

Remember:
My Project is a very large 3D environment where someone can provide lat/long then, I move my camera at that position. This require conversion which i have discussed in this caution that is not accurate. The environment is very large so I am also shifting the origin but whenever user try to set lat/long of the player/camera, I stop origin shifting and move back everything on its original position in order to carryout right conversion. Then, I again start origin shifting.

Edit:
Floating Origin Code:

 void Update()
{
    //As camera distance reached at certain limit set the environment parent position according to the inverse of camera local position
    if (AlllowShifting && CompareDistance())
    {
        ChangeEnvironmentPositionAtZero();//TODO Uncomment
    }
}

public void ChangeEnvironmentPositionAtZero() {

    Vector3 cameraInversePosition = new Vector3(camera.localPosition.x * -1f, camera.localPosition.y * -1f, camera.localPosition.z * -1f);//
    parent.transform.position = cameraInversePosition;

}

bool CompareDistance()
{

    distanceNow = Vector3.Distance(this.transform.position, origin.transform.position);
    return distanceNow > cameraDistanceLimit;

}

Note: All the objects are inside one main parent. The position is changing of the parent. While you can find Unity Co-ordinate conversion to GPS here.


texts: Unity polymorphism in editor through a list

texts:
So I have an ItemDatabase class which basically only has a list of Item

public class ItemDatabase : MonoBehaviour {
    public List<Item> Items = new List<Item>();
}

The Item class looks as follows:

[System.Serializable]
public class Item {

    public string Name;
    public int Id;
    public string Description;

    public Texture2D Icon;
}

Now I have some item types deriving from the Item class, for example Consumable

[System.Serializable]
public class Consumable : Item {
    public int Resore;
}

I next created a gameobject (empty) in my editor and hooked up my ItemDatabase to that object, providing a number of items in the list is no problem but I would like to make sure that - from my editor - I can choose a type of Item to put into the list, as of now, it only lets my add Item and not Consumable because it is a list of Item.

Can I also force the editor not to accept just Item by making it an abstract class?


texts:
I am trying to implement a simple game "Bulls and cows" in c#.
It is a final project of my university course about design patterns.
The target of the game is simple - try to guess the opponent number.

http://github.com/snoward/BullsAndCows

I try to follow the MVC and dependency injection patterns.
My problem is that I don't know what part of my program should be responsible for network connection. Is this a part of controller work?

I think that the best way is to create a new instance of network controller as server for my game. And then user choose UI to use (console or window). So, network controller must observe user's UI to update game model state.


texts: unity animation won't play unless input key is held

texts:
The code is simple. If the player presses the right arrow key, one animation clip plays. If the left arrow key, another clip plays, etc. However, the clip doesnt play fully unless the input key is held continuously. The second you release it, the second the clip stops playing. I think it's something to do with update() and the input not being remembered over next frame.

The code is simple:

using UnityEngine;
using System.Collections;

public class animatorcontroller_Logic : MonoBehaviour
{

    Animator anim;

    enum MovementState
    {
        Idle = 0,
        run = 1,
        walk = 2,
    }

    MovementState currentMovementState;

    void Start ()
    {
        anim = gameObject.GetComponent<Animator> ();
    }

    void Update ()
    {

        if(Input.GetButton("right"))
        {
            currentMovementState = MovementState.run;

        }

        else if(Input.GetButton("left"))
        {
            currentMovementState = MovementState.walk;

        }

        else
        {
            currentMovementState = MovementState.Idle;    //set movement state to idle
        }

        anim.SetInteger("MovementState", (int)currentMovementState);

    }

}


texts: What is the best way to implement host-migration application design?

texts: I'm trying to wrap my head around how any one of the clients could become a new host should the current host leave the game. I'm not looking for any code, but more of a high level application design of how a feature like this would work.


texts:
I'm working on a minecraft-like world and recently saw this video with a water shader.  I searched but couldn't find any good info on how to do something similar.  Maybe I'm just googling the wrong thing.  Does anyone have any resources on how to do something like this?

minecraft water shader video


texts: Isometric graphics with fake perspective

texts:
Diablo 2 is a game with isometric graphics. However, unlike other isometric games, D2 has the option to activate perspective. Obviously, the D2 developers found a clever trick to convincingly fake perspective in their isometric engine. It has to be a fake, because D2's graphics assets consist of pre-rendered isometric 2D tiles.

I want to implement a similar effect in my isometric graphics engine, but was unable to find out how to deal with the more subtle issues of applying perspective. A similar question has been asked on this site before. Unfortunately, the answer to that question does not help with the specific problems I am facing.

Let me explain my approach in detail. I use two dimensional tiles for floor and walls that look like this:
(Note that the floor tile is not actually part of the wall tiles. I added it just for clarity.)

These tiles can be assembled in 2D to create an isometric scene:

It is actually pretty easy to fake perspective in such an isometric scene. Slightly enlarging objects at the bottom of the screen and shrinking objects at the top makes them seem close or distant, and creates a subtle illusion of perspective. This is easily achieved in a vertex shader and works very well for floor tiles: .
The floor looks good, but the walls do not. Vertical lines get distorted. I can fix this by applying uniform scaling to objects, instead of distorting them like floor tiles. The scale factor depends on the object's y-position. This works well for character sprites and front facing walls, but fails for diagonal walls and more complex objects.

Now the actual question:

A front facing wall can be scaled by the y-coordinate of points A and B, which is the same. However, this does not work for corners or diagonal walls where the points have different y-coordinates.
It seems, for an accurate perspective effect, each wall tile needs to be treated differently so they can fit seamlessly together. This does not seem feasible to me. Ideally, I want to treat all wall tiles equally.

Is it possible to scale wall tiles so they fulfill the following criteria?

they should become continuously smaller the further up on the screen they are
they should not appear to move or jitter when the viewpoint changes
they should seamlessly fit together

Any help is appreciated. I've been worrying about this for days, but maybe I'm thinking too complicated :)

update:

Isometric view with increasing perspective. Note what happens when wall tiles are simply scaled. This works well for front facing walls only.

I want to approximate perspective correction so that all wall tiles fit seamlessly.


texts:
I have created an Animator and two sprite-based Animations. Both Animations preview correctly. In the Animator, I have created two states and two transitions between them based on a Boolean parameter. In the GameObject's script, the Boolean value is set based on distance to the player. When the player is far away Animation A plays and when the player is close Animation B plays.
However, while the transition from Animation A to B happens correctly when the player gets close, I only see the first frame of Animation B and it doesn't animate. If while in Play mode I preview Animation B (using the Animation window controls), it animates correctly.
Meanwhile, Animation A always plays correctly when it is supposed to.
What could cause this behavior? How can I get Animation B to play during runtime and not just when previewing? What's going on?
Edit:
Some screenshots. "Saw slow" is "Animation A" above, and "Saw fast" is "Animation B".

Animator

Animator State - Slow

Animator State - Fast

Transition: slow to fast

Transition: fast to slow

Animation - Slow

Animation - Fast
The code is very simple:
bool trigger = playerDistanceSqr < (activeDistance * activeDistance);
animator.SetBool("IsFast", trigger);


texts: How can I keep a consistent number of players per match in a continuous multiplayer game?

texts:
Fortnite Battle Royale is an example of a non-continuous multiplayer game. 100 players join a game which has fixed start and end times. When there's only one player remaining, the game ends.

Agar.io is an example of what I like to call a continuous multiplayer game. Players join in and die out, but the game goes on forever.

How would a game developer design a system to split players into different groups when there're too many online to fit in a single game? Let's say a game has a limit of 10 players, and 50 players are trying to join. The server will split them up into 5 separate groups. New players will be sorted evenly into these groups to replace players who died. When the player count increases past the global limit, new games will be created to fit them. The problem arises when the player count decreases. The system needs some way to seamlessly delete extra groups of players that are no longer needed. How can that be done without A) interrupting games to merge players together or B) block new players from joining into the group(s) that require deletion and waiting for everyone in it to die (which will be a bad experience for the last few players).

Agar.io obviously has a player population management system that works, so how do they do it?


texts:
In my game I have an quite irregular terrain at the bottom and a round ball which can be controlled by the keyboard. Is there any way to check, if the ball is currently on the terrain? This is very important to know because the ball should only be able to be controlled when it is on the ground.

I tried to use the OnCollision event of the ball body, but it only gets fired on the first occurrence.... For my problem a continuous type of collision-detection is needed.


texts:
I have the generic tessellation evaluation shader for triangles but I need to make it work for quads.  Is there any chance someone could explain what is happening here and point me in the right direction?

layout(triangles, equal_spacing, cw) in;
in vec3 tcPosition[];
out vec3 tePosition;
out vec3 tePatchDistance;
uniform mat4 Projection;
uniform mat4 Modelview;

void main()
{
    vec3 p0 = gl_TessCoord.x * tcPosition[0];
    vec3 p1 = gl_TessCoord.y * tcPosition[1];
    vec3 p2 = gl_TessCoord.z * tcPosition[2];
    tePatchDistance = gl_TessCoord;
    tePosition = normalize(p0 + p1 + p2);
    gl_Position = Projection * Modelview * vec4(tePosition, 1);
}

I understand that they're multiplying the control points (the original patch vertices) by the components of the new vertex (I guess relative to the patch verts?) and then normalizing the sum of these vectors to get the actual position of the new vertex which conforms to a nice unit sphere when applied to a cube of patches.  I want to extend this to work on quads: layout(quads, ...) in and add the tcPosition[3] vector but I don't really know how to get the same behavior with the fourth vertex.


texts: How to create a 2D region where sprites are automatically wrapped?

texts:
Edit

Finally managed to get this to work, after two separate questions! Here's a video demonstration:

http://www.youtube.com/watch?v=nZ7e0jegvs0

Will write an article about it later when I have a chance since there's a lot of little tricks involved. Thanks to everyone who helped figure this out. Meanwhile, the solution for the rendering part is described on this question, while for the physics part of the solution, check this other question.

Disclaimer

I'm looking for intelligent solutions that encapsulate this behavior in a way that is transparent to the user. Don't simply answer "draw the sprite four times". For instance, something that could be packed up in a class like:

class Sprite
{
    Vector2 Position;
    float Rotation;
    float Scale;

    Texture2D Texture;

    Rectangle? WrapRegion;

    void Draw(SpriteBatch spriteBatch);
    bool IsColliding(Sprite other);
}

By the way, there's no need to post any code, just a description of how to solve each of the problems will do.

Problem

1 - By wrapped I mean that when they leave the borders of that region, they continuously appear on the opposite side, i.e:

So simply changing the sprite's position clearly is not enough. The sprite might have to be drawn either 2 or 4 times depending on its position in relation to the region.

And despite needing to draw it several times, I should still be able to do, for instance:

sprite.Position += Vector2.One; // Every frame

And the sprite's Position would automatically wrap within the area.

2 - Another problem would be how to handle collisions between wrapped sprites properly. For instance:

This should trigger only one collision (okay, consider that they are overlapping a bit although the drawing might not suggest it).

Checking for the collision manually shouldn't be too hard.

But the bigger problem arises when using this together with a physics engine (which is what I tried to do before and failed). How would I coerce the physics engine into handling this problem correctly, since there's usually a 1 to 1 correspondence between the physics body and the sprite representation?

Edit

You can see the solution to this particular point here. I create 9 bodies attached to each other using the joint described in that question, like so:

3 - Finally, and being more specific about XNA in this case, if the wrap region happens to be smaller than the Viewport, what would be the best way to clip the sprite so that it does't show outside the region anywhere?

Take into consideration that the sprite may be rotated or scaled too.


texts:
I have an enemy which shoots 3 different kind of bullets. They are of different sizes, speed, and representation (rectangle, oval, and a more classic bullet).

Should they be 3 separate classes or just 1?

If a single class, how would I implement it?


texts: Getting multiple inputs in C++ simultaneously using kbhit() function

texts:
I am using Turbo C++ to make a game using the graphics.h library (I know it's a bit old). In this game, the player can move left, right and they can jump using A, D and W (just like in Super Mario).

I am using the kbhit() function to get inputs from user. The problem with it is that I cannot jump and move the character at the same time (so it moves in a parabolic trajectory).
How can I take multiple inputs so that, for example, if I press W and D, character will jump towards right?

The code is given below:

if(kbhit())
{
    ch=getch();

    if(ch=='e'){break;}   //exit

    if(ch=='d')           //move right
    {
    ax=1;
    if(vx<vellim){vx=vx+ax*dt;}
    dx=vx*dt;
    x+=dx;
    s_mario(x,y); //This function draws the character at the appropriate place

    }

    if(ch=='a')             //move left
    {
    ax=-1;
    if(vx>-vellim){vx=vx+ax*dt;}
    dx=vx*dt;
    x+=dx;
    s_mario(x,y);
    }

    if(ch=='w'&&jumpkey==0)   //jump
    {
    vy=60;
    jumpkey=1;
    }

}

if(jumpkey==1)
{
vy=vy-g;
dy=vy*dt;
y-=dy*0.1;
if(y>400){y=399;vy=0;jumpkey=0;}
s_mario(x,y);

}

if(!kbhit())
{       vx*=c;
    dx=vx*dt;
    x+=dx;
    s_mario(x,y);
    delay(5);
}


texts: Multiple render targets: Output target format performance questions

texts:
This is probably API independent (more dependent on hardware implementation), but just in case, I'm using OpenGL.

The question is restricted to PC hardware.

I have a couple of questions concerning the output textures that are being rendered to (e.g. in gbuffer geometry pass)

Is there a (noticeable, measurable) performance penalty of using different formats for the
different output textures? e.g. RGB8 (unsigned byte) (8 bits for each component) for diffuse color, RGBA8 (unsigned byte) for specular color + roughness, RGB16F for normals?
Is it worth it to pack smaller component data into larger types just so I can have equal render targets (and fewer of them in number)? E.g. just having two RGBA16F render targets, packing diffuse + specular + roughness into the first, and normals and other stuff into the second render target using bitmasking?
Are there output texture data types/formats that I should avoid entirely?


texts: How do I make players believe they're doing something wrong even when they're not?

texts:
You're doing it right. …right?

In the game Cart Life, you are led to consider this, even though you are doing fine. This effect is created by making you do mundane jobs, earn little money, and have and things happen that feel like your fault.

Is there a better way than life-like mundane and unfortunate encounters to make you feel like you're failing at the game? I want to use this to mess with how my players play the game. Overwhelm them. Make a little success feel huge. Make them feel depth. Any ideas?


texts:
Where can I find good (well organized) examples of game code? I'm hoping that I can pick up some organizational tips. Most examples in books are too short and leave out lots of detail for the sake of brevity. I'm particularly interested on how to group your variables and methods so that another programmer would know where to look in the code. For example initializers at the top, then methods that take input, then methods that update views.

I don't care about a particular language, as long as its OOP. I looked at the Quake 2 and 3 sources, but they're straight C and not much help for getting tips on organizing your objects.

So, have you seen some good source? Any pointers to code that makes you say "wow, that's well organized" would be great.


texts: How can I achieve glow effects similar to those in  WoW?

texts:
I've recently implemented a glow effect using a gaussian filter and could not get the full effect I was wanting. I'm curious to know if how certain glow effects are done in WoW. Like this image:

Around the sword is a really nice glow effect. How might this be done? Also, sometimes in WoW you see these glow effects take a life of there own. Like the purple glow in this pic:

Are these accomplished with particle effects?
Are there any good resources/tutorials that could help with someone to learn how to do these effects?


texts: smooth loading of the heavy scene in unity3d

texts:
I have a very very big/huge scene to load, I can't load it at once. So what I know I have applied but it still loading takes  some time I want to make it smooth. How it possible?

What i have tried so far is I divided the scene into multiple scenes and loading it into async manner as my character controller move. I am moving my character controller and accordingly loading (its near)scenes by matching its position.

How do i load smoothly a big scene? what will be the strategy? Is this right strategy which I am doing or there any else solution.


texts: Should I use a database for storing game content?

texts:
I have a 2D Game written in C++ using SFML.  I want to make the game expandable in such a way that content like items or entities could easily be added by adding a line/entry/row to a file or database.

I am looking for something that does not need to be compiled into the program, but instead can be read from and written to at runtime.  When would it be appropriate to use a database?


texts: Which array does dstArrayElement refer to in the VkWriteDescriptorSet structure?

texts:
Here is the link of VkWriteDescriptorSet structure from vulkan specification:
https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkWriteDescriptorSet.html
Text pertaining dstArrayElement

dstArrayElement is the starting element in that ARRAY. If the descriptor binding identified by dstSet and dstBinding has a descriptor type of VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT then dstArrayElement specifies the starting byte offset within the binding.

I want know which array this statement is refering to?


texts: What is the name for the technique to use different palettes for different tiles of a screen?

texts:
I've found the keywords "subpalette" and "PPU palette", but they seem to be NES-specific. Though the idea of using a small palettes table and use 2 bits per pixel in an image (+ few bits reference to a palette per tile) looks like a cool retro compression method with low decompression drawbacks, so I guess it was used more widely.
Does this technique (of using different palettes for different blocks of pixels) have a name? Does it have a usage apart from NES?


texts: How should I represent a tile in OpenGL-es

texts:
Let me start with I am currently learning OpenGl-es using Android.

I have been having the hardest time trying to design a simple and logical way of making tiles (2d flat polygons). The tutorials tell me to just keep the polygon as a float array of veticies:

private float vertices[] = {
      -1.0f,  1.0f, 0.0f,  // 0, Top Left
      -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
       1.0f, -1.0f, 0.0f,  // 2, Bottom Right
       1.0f,  1.0f, 0.0f,  // 3, Top Right
};

That in and of itself is easy enough. I modified the code to suit my desired polygon and it drew fantastic. Now I wanted to draw more tiles and have a scrolling feature (look around the world). But I'm not sure what's the best way to do so.

Should I leave every tile with a float array of indices and when it comes time to move the tile, directly modify thefloat values?

Is it a good idea to create an ArrayOfPoints (Point just being a container for exactly 3 float values) class to hold all of the points and then have methods that cycle through the points and change their values in a more safe fashion?

Does anyone have any tutorials on simple tile based map building so I can look at how they do their maps?

(Note: these questions are based on what I have read on animating. That is to say that you change the coordinates of the object in relation to the origin and leave the camera at 0,0,0. If it is more proper to just leave objects where they are, I guess my question loses value.)


texts: How to use generic level editors with my arbitary code?

texts:
I have a game, breakout clone. It has a Block class that contains CCSprite as a property.
Usually I made levels by manually setting those blocks to positions.
Here comes the question, how do I use generic level editors with my custom code? All editors work with CCSprites and not my class. How can I overcome that?


texts: In Eclipse using libgdx, what does "project description file is missing" mean?

texts:
In a sudden case of nostalgia, I switched my eclipse workplace from my working libgdx projects to an older one. After looking through my old stuff I had some problems switching it back, since I didn't import it right. After I got that working, I cant run my libgdx desktop projects anymore. It says it couldn't load the Spritesheet anymore: After googling a little, I was told to make sure the Android asset folder is linked to the desktop project, which it is.

I then noticed that one of the project folders is closed (I've got Project-android,Project-core,Project-desktop and just Project) The folder project was closed and when trying to open it, it gave me the following error:

  The project description file (.project) for 'Projekt Stella' is missing. This file contains important information about the project. The project will not function properly until this file is restored.

The thing is I made sure that this file is still in the folder which it is... so now I have no idea how to get this working. Any ideas?

Edit: The project works fine in Android studio. Its just not working in Eclipse.


texts: Is it better to preserve scenes in memory or recreate them every time I need them?

texts:
I am using Cocos Builder to create scenes using sceneWithNodeGraphFromFile:owner:. Now I have doubts about whether it's better, on iOS, to save some memory or CPU cycles. In other words I have two options:

First, I could do lazy initialization of scenes without removing them from memory, like this:

- (CCScene*) myScene
{
    if(!_myScene)
        _myScene= [CCBReader sceneWithNodeGraphFromFile: @"MyFile.ccbi"];
    return _myScene;
}

Then I always call self.myScene and I possibly set _myScene to nil if the app receives a memory warning. I never remove a scene from the director, I just push without cleaning.

Or, I could initialize a new scene every time. I'd call sceneWithNodeGraphFromFile:owner: every time that I need to push a scene, popping and cleaning it from the director and creating it again if I need it.

Which should I prefer and why?


texts: Storing a List to PlayerPrefs Not Working

texts:
I have a test database of 37 records and I have stored each column into a list and I am storing each record into PlayerPrefs.

void storeStarData()
{
    // Code to store star data in PlayerPrefs...
    PlayerPrefs.SetInt("totStars", NumOfStars);
    int i = 0;
    while (i < NumOfStars)
    {
        PlayerPrefs.SetString(("starID" + i), StarIDID[i]);
        PlayerPrefs.SetString(("starName" + i), StarName[i]);
        PlayerPrefs.SetString(("starHIP" + i), StarIDHIP[i]);
        PlayerPrefs.SetString(("starHD" + i), StarIDHD[i]);
        PlayerPrefs.SetString(("starHR" + i), StarIDHR[i]);
        PlayerPrefs.SetString(("starGL" + i), StarIDGL[i]);
        PlayerPrefs.SetString(("starBF" + i), StarIDBF[i]);
        PlayerPrefs.SetString(("starRA" + i), StarRA[i]);
        PlayerPrefs.SetString(("starDec" + i), StarDec[i]);
        PlayerPrefs.SetString(("starMag" + i), StarMag[i]);
        PlayerPrefs.SetString(("starCI" + i), StarCI[i]);
        PlayerPrefs.Save();
        i++;
    }
    PlayerPrefs.Save();
    Debug.Log(PlayerPrefs.GetString("StarID0"));
    Debug.Log(PlayerPrefs.GetString("StarID1"));
    Debug.Log(PlayerPrefs.GetString("StarID2"));
    Debug.Log(PlayerPrefs.GetString("StarID3"));
    startSimulation();
}

First record in list StarIDID[0] = 1
Last record in list StarIDID[36] = 37

At the end, I've added 4 Debug.Logs that return the IDs of the first 4 stars. For some reason, only the first StarIDID is being stored into Player prefs.

Here is the output of the Debug.Log:

As you can see, StarID0 is the only PlayerPref with a valid value stored, the other ones don't have any values stored in them for some reason.

Is there a way to fix this and am I doing anything wrong here?


texts:
Say I use a basic ES approach, and also inside Systems I hold lists of all entities that Systems are required to process.

How do I maintain this list of entities in desired rendering order, i.e. for a dumb 2D RenderingSystem?

I saw this discussion, and what they suggest is to do something like Z ordering - what I would probably do is just to store a "layer" int in DrawableComponent and then, inside RenderingSystem, just sort entities by mentioned "layer" whenever the entity list for RenderingSystem changes.

They also say we could just delete and recreate the entity whenever we want it on the top, but it seems too inflexible to me.

How is this problem usually solved?


texts:
I apologize for the subjective "best" keyword.

My friend and I have started creation of a 2D adventure game. It will be top-down in the style of pokemon or zelda (just the perspective). We have been discussing methods of creating a large world-map that the player can traverse without straining the memory capabilities of our machine.

Our first impulse was to create a large map and a circle around the player in which content will be loaded. We figured this won't hold for long and decided to partition the map into sections. First we had four large sections, but realized we could simply break it down into many tiny sections.

I played some Zelda from the SNES and saw that, during the shift of a map, the content could be loaded just then. What I mean is, instead of just checking a rectangular area for data to load, we simply section the map into many tiny chunks that load and de-load data as we move from map-portion to map-portion.

Today, he told me he wanted to create a simply 2D array map[WIDTH][HEIGHT] that contains data about every grid in the game and is a constant save-to-disk operation for data that we don't need.

I'm not sure about these ideas and thought that I might as it here. Any links, resources or tutorials on the subject would be greatly appreciated as well as direct answers to our question on how to do it efficiently.


texts: How can I separate entities from their actions or behaviours?

texts:
I'm having a go at creating a very simple text based game and I'm wondering how I can design the entities (characters, sentient scenery) with regards to the actions those entities can perform.

As an example, I have an entity that is a 'person' with various properties such as age, gender, height, etc. This 'person' can also perform some actions such as speaking, walking, jumping, flying, etc etc.

How would you separate out the entity from the actions it can perform?


texts: Is there a way of making the Unity editor paint decals on surfaces?

texts:
I see other engines can do this, here's a video of what I would like to achieve :

I think the one on the image uses something that blends the surface and the image, but I just want to be able to paint a image on a surface.

How can I do this within the unity editor ? :)

Edit : Here's another video that kinda shows what I want to do. (Click me)

(I want to code it myself, I don't want some kind of downloadable asset :P )


texts: I've been trying to make something so that when you press a button, a cube appears. Problem is, whenever I jump on said cube, it sends me flying away so far my character gets deleted (not a game mechanic). I have noted that this problem only arises when the object mode is in movable, this does not happen when it is static. (I am using AddActorWorldOffset, so it is necessary). Any help would be appreciated!


texts: How to create additional rooms for new play sessions in a 2-player online game on Node.js?

texts:
I'm creating a 2-player online game using Node.js with Express and Socket.IO

My task is to create a new room when 1st, 2nd, etc ... rooms are full. From this article
I know how to create one room for all connections:

// require everything you need
var io = require('socket.io').listen(server);
io.on('connection',function(socket){
    // creating socket.player with unique ID
    socket.on('anyeventfromconnectedplayer', function doSomething () {...
    });
});

How to create new rooms for new play sessions?

Socket.IO has a mechanism to implement the thing I need but I  don't understand how to use it correctly.


texts: How do I change a bool value once an animation has played?

texts:
I've designed a Dodge behavior for my player. On input the behavior is executed setting "isDodging" bool to true. My Animation also plays when "isDodging" is true.

I need a proper way to set "isDodging" to false once the Behavior is complete. Currently "isDodging" becomes false once touching the ground is detected, but I think the best way to handle this would be once the animation is complete or the animation has been canceled into a different behavior. What steps would you recommend?

using UnityEngine;

public class Dodge : AbstractBehavior
{
    public float speed;
    public bool isDodging;

    private void FixedUpdate()
    {
        var canDodge = inputState.GetButtonValue(InputButtons[0]);

        if (!isDodging && canDodge)
            OnDodge();

        else if (isDodging && collisionState.standing)
            isDodging = false;
    }

    protected virtual void OnDodge()
    {
        var velocityX = speed * (float) inputState.direction;

        isDodging = true;
        body2D.velocity = new Vector2(velocityX, body2D.velocity.y);

    }
}


texts:
I once tried to write a simple game with UDP in a week as a throwaway test. It went horribly.

I threw it away early. The main problem i had was restoring the game state of all players/enemies/objects to an old state and fast forward the game to the point of time the player is playing (ie half a second before a jump. A little early or late can make the player miss the jump)

Maybe this method is not the easiest way? i suspect it to be but i designed it wrong from the beginning and realized at the end of 2nd day. (so i didnt learn too much or wasted that much time)

For myself and others, What is involved for a simple UDP game and how do i write one? Or how do i solve the prediction problem restoring to state properly.

I'll mark this as CW bc i know there will be lots of helpful answers.


texts: How "fake" do invented names of a football game have to be in order to avoid copyright infringement?

texts:
I know that real player names cannot be used in videogames unless the authorization (generally very expensive) has been given by the holders of the rights (players, teams etc.)

as explained here and here.
There is a discussion here about possible sources that can be consulted in order to figure out whether you are infringing any copyright issue, but it does not say anything specific about my problem (at least as far as I understood it, given my poor comprehension and expertise on the matter).

my question is very simple: is there any rule that determines the amount of difference (in characters, sound, length, phonological features, whatever) from a real name to a fictitious (or fake) name in order for the latter to be considered really fake?

For example, if I created a football videogame in which there is a strong offensive midfielder that has Cristiano Ronaldo's features (with respect to characteristics, statistics etc. not physical appearance) how could I call this player to avoid copyright infringement?

Cristian Ronald?
Cristo Romaldi?
Christiano Ronnaldo?

there was a famous release of ISS PRO (football game) employing fake names - here's the list - that were very similar to real ones.

Is there a specific rule/law that says which is good and which is not?


texts: i've used opengl core profile for a while now and i was wondering if it was possible to create a "decent" application (like a game/game engine) with good graphics. I have a machine which can run only OpenGl 2.1(raspberry pi3), i already know the advantages of core profile, but is Opengl 2.x still usable for today's standards?


texts: How can I instantiate objects with gaps between all objects?

texts:
When instantiate each a new object I want it to be with the same gaps from also the other instantiated objects.

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

public class GenerateStairsUnits : MonoBehaviour
{
    [Header("Stairs Units Prefab")]
    public GameObject stairsUnitsPrefab;
    [Space(5)]
    [Header("Settings")]
    [Range(1, 20)]
    public int numberOfUnits = 1;
    public static GameObject Unit;
    public int gap = 10;

    private int oldNumberOfUnits = 0;
    private List<GameObject> units = new List<GameObject>();
    private GameObject unitsParent;

    // Use this for initialization
    void Start ()
    {
        oldNumberOfUnits = numberOfUnits;

        unitsParent = GameObject.Find("Stairs Units");
        for (int i = 0; i < numberOfUnits; i++)
        {
            Unit = Instantiate(stairsUnitsPrefab, unitsParent.transform);
            Unit.name = "Stairs " + i.ToString();
            Unit.transform.localPosition = new Vector3(gap, 0, gap);
            units.Add(Unit);
            Unit.AddComponent<MoveObjects>();
        }
    }

    private void Update()
    {
        if (numberOfUnits < oldNumberOfUnits)
        {
            Destroy(units[units.Count - 1]);
            units.RemoveAt(units.Count - 1);

            oldNumberOfUnits = numberOfUnits;
        }
        else
        {
            for (int i = oldNumberOfUnits; i < numberOfUnits; i++)
            {
                Unit = Instantiate(stairsUnitsPrefab, unitsParent.transform);
                Unit.name = "Stairs " + i.ToString();
                Unit.transform.localPosition = new Vector3(gap, 0, gap);
                units.Add(Unit);
                Unit.AddComponent<MoveObjects>();
            }

            oldNumberOfUnits = numberOfUnits;
        }
    }
}

I tried in both places to add a localPosition with gap/s:

Unit.transform.localPosition = new Vector3(gap, 0, gap);

But they are still all at same position.


texts: Understanding how texCUBE works and writing cubemaps properly into a cube rendertarget

texts:
My goal is to create accurate reflections, sampled from a dynamic cubemap, for specific 3d objects (mostly lights) in XNA 4.0.

To sample the cubemap I compute the 3d reflection vector in a classic way:

    half3 ReflectionVec = reflect(-directionToCamera, Normal.rgb);

I then use the vector to get the actual reflected color:

    half3 ReflectionCol = texCUBElod(ReflectionSampler, float4(ReflectionVec, 0));

The cubemap I am sampling from is a RenderTarget with 6 flat faces.

So my question is, given the 3d world position of an arbitrary 3d object, how can I make sure that I get accurate reflections of this object, when I re-render the cubemap. Should I build the ViewProjection matrix in a specific way? Or is there any other approach?


texts: Can you create a viable two player turn-based networking implementation using only REST API for outbound and push for inbound data? If a game is comprised of, on average, 30 moves, is it a bad idea to just send 15 push notifications to each user? If hosting expense is less than income for each DAU, is this perfectly acceptable, or an abuse of what push is intended for?  ...Why or why not?


texts:
I created a little pool in order to better manage my enemies, to which, an enemySpawner object calls to retrieve a clone and show it on screen

public class ObjectPool : MonoBehaviour
{
    public static ObjectPool current;
    public GameObject objectForPool;
    public int poolAmmount = 20;
    public bool growth = true;

    List<GameObject> objectsForPool;

    void Awake()
    {
        current = this;
    }

    // Use this for initialization
    void Start ()
    {
        objectsForPool = new List<GameObject>();

        for (int i = 0; i < poolAmmount; i++)
        {
            GameObject obj = Instantiate(objectForPool);
            obj.SetActive(false);
            objectsForPool.Add(obj);
        }
    }

    public GameObject GetPooledObject()
    {
        for (int i = 0; i < objectsForPool.Count; i++)
        {
            if (!objectsForPool[i].activeInHierarchy)
            {
                return objectsForPool[i];
            }
        }
        if (growth)
        {
            GameObject obj = Instantiate(objectForPool);
            objectsForPool.Add(obj);
            return obj;
        }
        return null;
    }

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

    }
}

The call(EnemySpawner update)

void Update ()
{
    transform.position = new Vector3(transform.position.x + (speed * Time.deltaTime), 0, transform.position.z);
    if (transform.position.x <= boundary.xMin || transform.position.x >= boundary.xMax)
        speed *= -1;

    if (Time.time > nextSpawn)
    {
        nextSpawn = Time.time + spawnRate;

        GameObject clone = GetComponent<ObjectPool>().GetPooledObject();
        if (clone == null || clone.activeInHierarchy) return;
        clone.GetComponent<EnemyMovement>().SetPlayerShip(playerShip);
        clone.transform.position = transform.position;
        clone.transform.rotation = transform.rotation;
        clone.GetComponent<Health>().RestoreHealth();
        clone.SetActive(true);
    }
}

The problem here is, that my enemies are being deactivated on mid trajectory

https://youtu.be/ZGHC6wwGX1E

I know my issue is in my pooling, but I can't figure out what I'm doing wrong


texts: How to make async step timing (game loop) using Box2D and C++

texts:
I'm making a game in C++ using Box2D and WebSocket++. The world needs to updated every 1/60 second. Meanwhile the WebSocket server handles players. How I should make the interval? I know there's no setInterval function in C++, but I can do something like this:

• make async function - https://stackoverflow.com/questions/33234403/using-setinterval-in-c/33234557

• make async thread - https://codereview.stackexchange.com/questions/40915/simple-multithread-timer

or maybe there's a lib?

Note: this isn't a duplicate of How should I write a main game loop? because here I need asynchronous game loop. In linked topic there are synchronous game loops.

Why I won't use while (sync loop):

commands after while (loop) are never excuted if loop is set to true.


texts:
While programming and not being able to compile because of a missing Template struct or class in a hlsl file, i tried to search for ConstantBuffer but had no luck.
Is there any light to be shed about it. Ive dug for a while and cannot find anything.
Im in Directx 12 C++
example snippet...
    #define HLSL
#include "RaytracingHlslCompat.h"
#include "RaytracingShaderHelper.hlsli"
#include "RTAO/Shaders/RTAO.hlsli"

Texture2D<float> g_inValue : register(t0);
RWTexture2D<float2> g_outMeanVariance : register(u0);

RWTexture2D<float4> g_outDebug1 : register(u3);
RWTexture2D<float4> g_outDebug2 : register(u4);

ConstantBuffer<CalculateMeanVarianceConstantBuffer> cb: register(b0);


texts: Check if triangle collides with any object in certain LayerMask

texts:
I am creating a custom navigation mesh and in order to see which triangles in my mesh are traversable I need a way to check if anything on a certain LayerMask in my scene collides with my triangle.
I have already thought about using consecutive SphereCasts to "fill in" my triangle, but this seems needlessly complex and computationally slow. Is there a built in function in Unity to achieve this?


texts: How do Axis-Aligned Bounding Boxes update with rotations?

texts:
I have a bounding box class with a min (x,y,z) and max point (x,y,z). The object that is being rotated has a rotation matrix (3x3 matrix), but I don't know how to update the bounding box with rotations.

I'm also a little confused if I should be using Oriented Bounding Boxes instead. For example, if the 3D object is a cube then the bounding box would rotate with it so they share the same 8 vertices at whatever rotation the cube is in.

What's the best way to represent the bounding box for rotations and test for collisions?


texts: Multi threaded game - updating, rendering, and how to split them

texts:
From the StackOverflow post (it was recommended I move this):

So, I'm working on a game engine, and I've made pretty good progress. However, my engine is single-threaded, and the advantages of splitting updating and rendering into separate threads sounds like a very good idea.

How should I do this? Single threaded game engines are (conceptually) very easy to make, you have a loop where you update -> render -> sleep -> repeat. However, I can't think of a good way to break updating and rendering apart, especially if I change their update rates (say I go through the update loop 25x a second, and have 60fps for rendering) - what if I begin updating halfway through a render loop, or vice versa?


texts: Can I test for containment of convex polyhedra with the separating axis theorem?

texts:
I would like to refine the output of the separating axis test to not only tell me whether convex polyhedron A intersects convex polyhedron B, but also whether A is completely inside B. Is it safe to say that if A's corner points' projections (onto the separating axes) are always inside B's corner points' projections, A is inside B?

Also, is this the standard way to do combined intersection + containment tests?


texts: Is it possible to develop web-based games using Corona SDK?

texts:
Some clients asked me to develop 2D web-based games and later on they might want to release those games on mobile platforms.

I know Corona and I don't want to rewrite my code twice. Is it possible to create web-based games using Corona (the free SDK)?