texts: Fine-tuning parallaxing objects in 2D games

texts:
I'm making a 2D platformer game and I'm having a hard time figuring out how to fine-tune parallaxing objects in-game quickly enough. Problem is I don't even know how to make it faster, so I'm basically looking for standard approaches.

Currently I place a parallaxing object just like a normal static doodad somewhere on a level and then define the parallax offset multipliers (horizontal and vertical). Then I spend from five to ten minutes moving the camera around the location finding three values that satisfy me. So when placing each object takes that long, you start thinking of a way to make it faster, but unfortunately, I couldn't come up with anything better than what I have, so I'd like to learn about other approaches and possibly improve mine with that knowledge.

What are the usual approaches to placing and tuning the parallaxing objects in 2D games?


texts:
I'm trying to render an obj file with a VBO but I have some problems. I have a Renderer object that has a method "setPositions()" that simply stores some data from a QVector to a VBO. The render part is in another method. I couldn't render anything, so I wanted to check if the array was really copied in the VBO. Instead of working on the Qvector, I wrote this simple code to make some test to render a simple square. As you guessed, the bufferSize variable is still at 0, and I have no render.

     /* setPositions() */
     float vertices[] ={
          0, 0, 0,
          100, 0, 0,
          100, 100, 0,
          0, 100, 0
     };
     glGenBuffers(1, &pos); // Gluint pos : class attribute

     glBindBuffer(GL_ARRAY_BUFFER, pos);

     glBufferData(GL_ARRAY_BUFFER,
                   12 * sizeof (float),
                   NULL,
                   GL_STATIC_DRAW);
     glBufferSubData(GL_ARRAY_BUFFER,
                      0,
                      12 * sizeof (float),
                      &vertices[0]);

     int bufferSize = 0;
     glGetBufferParameteriv (GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bufferSize);

     if (bufferSize != (12*sizeof(float)))
     {
          glDeleteBuffers (1, &pos);
          std::cout << "sizes mismatch. Buffer: " << bufferSize << " Array : " << 12*sizeof(float) << std::endl;
     }

     glBindBuffer (GL_ARRAY_BUFFER, 0);

     /* render() */
     glBindBuffer (GL_ARRAY_BUFFER, pos);

     glEnableClientState (GL_VERTEX_ARRAY);

     glVertexPointer (3, GL_FLOAT, 0, BUFFER_OFFSET (0));

     glDrawArrays (GL_QUADS, 0, 4);

     glDisableClientState (GL_VERTEX_ARRAY);

     glBindBuffer (GL_ARRAY_BUFFER, 0);

Does somebody have an idea ?


texts: Unity: Z-position issue on gameobject with subcomponents

texts:
I'm following this tutorial from Ryan Miller on how to create a rig of sorts from a sprite atlas sheet.

My intention was to put the panda behind a bamboo, but this is what happened:

The bamboo's Z-position has been set to 2, whilst the Panda's has been set to 6.

Here's a 3D look at the problem:

How do I fix this?


texts: SHMUP: who's in charge of collision detection?

texts:
Simple design question here:

In a Shoot'Em Up, where you often have to deal with hundreds of bullets / missiles / weird flying stuff, who's in charge of detecting collisions? The weapon or the ship?

As there is usualy less ships than bullets displayed on screen, I tend to believe that would be smarter if ships could be in charge of it. But is it really smarter?


texts: Quaternion.slerps resets camera rotation to (0,0,0) when i go to play mode help!

texts:
i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want.
This is the camera rotation i have set:

This is rotation of character my script is attached to:

And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternions.

this is the script:

    public class ScreenCharacterController : MonoBehaviour {

     private Camera mainCamera;
     private CharacterController character;
     private int leftFingerID = -1;
     private int rightFingerID = -1;
     private Vector2 leftFingerInput;
     private Vector2 rightFingerInput;
     private float xAxisRotation;
     private float yAxisRotation;
     [SerializeField] private float minXRotation;
     [SerializeField] private float maxXRotation;
     [SerializeField] private float minYRotation = -25f;
     [SerializeField] private float maxYRotation = 25f;
     [SerializeField] private float cameraRotationSpeed = 20f;

     void Start()
     {
         mainCamera = Camera.main;
     }

     void Update()
     {
        //for touch
         TouchInput();

        //for calculating rotation vaues
         CalculateAndClampRotation();

         RotateCamera();
     }

     void TouchInput()
     {
         foreach (Touch touch in Input.touches)
         {
             if (touch.phase == TouchPhase.Began)
             {
                 //Left Touch
                 if (touch.position.x < Screen.width / 2)
                 {
                     leftFingerID = touch.fingerId;

                 }
                 //Right touch
                 else
                 {
                     rightFingerID = touch.fingerId;

                 }
             }
             else if (touch.phase == TouchPhase.Moved)
             {
                 //Left Touch
                 if (touch.position.x < Screen.width / 2)
                 {
                     if (leftFingerID == touch.fingerId)
                     {

                     }

                 }
                 //Right touch
                 else
                 {
                     if (rightFingerID == touch.fingerId)
                     {
                         rightFingerInput = touch.deltaPosition * Time.smoothDeltaTime;

                     }

                 }
             }
             else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
             {
                 if (touch.fingerId == leftFingerID)
                 {
                     leftFingerID = -1;

                 }
                 else if (touch.fingerId == rightFingerID)
                 {
                     rightFingerID = -1;
                     rightFingerInput = new Vector2(0, 0);
                 }

             }
         }
     }

 void RotateCamera()
     {
         Quaternion currentRotation = mainCamera.transform.localRotation;
         Quaternion targetRotation = Quaternion.identity;

         targetRotation = Quaternion.Euler((mainCamera.transform.localRotation.x - yAxisRotation),
         -(mainCamera.transform.localRotation.y - xAxisRotation), 0f);

         mainCamera.transform.localRotation = Quaternion.Slerp(currentRotation, targetRotation, 0.5f);

     }

     void CalculateAndClampRotation()
     {
         xAxisRotation += rightFingerInput.x * cameraRotationSpeed;
         yAxisRotation += rightFingerInput.y * cameraRotationSpeed;
         xAxisRotation = Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation);
         yAxisRotation = Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation);
     }

 }


texts: Share a function between two passes inside CG Shader for unity3d

texts:
I'm writing a shader in CG language for Unity3d.
When making transparent object you need to create two similar passes in SubShader. First to render only back faces (with Cull Front) and second to render only front faces  (with Cull Back). But the code for vertex and fragment function is the same.

Is it possible not to double a code and declare some functions, that would be shared between passes?
I want to have something like in my code example.

Shader "cool shader" {
Properties {
    ...
}
SubShader {

    CGPROGRAM
    // need to declare vertexOutput somewhow here
    float4 sharedFragFoo(vertexOutput i) : COLOR  // How to make smth like this?
    {
        ....
        return float4(...);
    }
    ENDCG

    pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        vertexOutput vert(vertexInput v) {
            vertexOutput o;
            ...
            return o;
        }

        float4 frag(vertexOutput i) : COLOR
        {
            return sharedFragFoo(i); // call the shared between passes function
        }

        ENDCG
    }

    pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        vertexOutput vert(vertexInput v) {
            vertexOutput o;
            ...
            return o;
        }

        float4 frag(vertexOutput i) : COLOR
        {
            return sharedFragFoo(i); // call the shared between passes function
        }

        ENDCG
    }
}
}


texts:
I have a while loop that goes for ever. The goal is if I press A button, a message should be printed out showing this button has been pressed A has been pressed. I've done the loop and connecting XBox controller but the problem is that the message is printed out many times if I press the button one time. My question is why the message is being shown many times while I just press the button one time? Should I make some kind of sleep?

Edit:
This is the part of the code

while(true)
    {
        if(Player->IsConnected())
        {
            if( Player->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_A )
                std::cout << " A button has been pressed ..." << std::endl;
        }
        else
        {
            std::cout << "\nERROR: Connect XBox Controller ... \n";
            std::cout << "Press Any Key To Exit.";
            std::cin.get();
            break;
        }
    }

The result when I only press once.

Press A to be printed out ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...
 A button has been pressed ...


texts: Speed up the DirectX game - how else can I boost the fps with typical triangle drawing?

texts:
I am writing my own c++/DirectX engine. I've made the basic framework and here comes the time for optimizations.

I don't want to focus on optimizing the resources themselves right now (meshes, textures) or on instancing. I've also commented out shadows and normal mapping for that test. So it's just a "flat" problem of "how to speed up rendering that vertices?".

The meshes are fully static, loaded from files (no terrain generation involved).

I just have about 120.000 triangles with textures on scene (one shader, few models). And on my laptop I get about 20-40fps. I was able to increase fps with vsync and back-face a bit (note that camera is rotating and fps falls when all 120.000 triangles are within its range):

Still, other engines (Unity, Unreal) can render the same meshes faster on the same hardware (and Unreal does it even faster then Unity which still is better then my DirecX11/c++ implementation). How they do that? I know there are many "pro programmers" behind that engines, but they are no magicians. And some solutions should be possible to apply in my engine too (vsync was easy to apply yet it gave me a nice speed boost).

I use DirectX 11, c++. I use Visual Studio if it's important. There is very little logic involved in application, no physics, no searches etc. that could slow down the render loop.

So far I made just few optimizations:

Dynamic/static vertex buffers where they are needed. Index buffer.
Back-face culling.
V-SYNC (more about removing bugs but also helped with fps a bit).
Near/far clipping.
Compressing textures into single texture atlas (I've not done it yet, but I am aware of that technique).
Lowering the AA (e.g. MSAA) and resolution (but it has an big impact on render quality).

I know my hardware is capable of rendering such amount of triangles. But how to help it? My problem is that I don't know all the tricks & methods that can be used here.

If any part of the source code would be useful, just comment me (I'm not sure which parts should I post and I don't want to paste meaningless code listings). I will post the results of fps increase/decrease as I manage to incorporate new optimizations.


texts: How to smoothly move camera when the player is climbing a diagonal staircase in 2D tile-based side-scroller?

texts: I am working on a game, which is tile-based, similar to the way Terraria works. My player is 2 x 3 and can move over one-high obstacles, but this creates a very jittery effect, since my camera currently strictly follows the player. I was thinking of either somehow implementing a smoother camera movement or overhauling the player movement itself. I would love some feedback on how one might go about fixing this.


texts: How do I calculate speed given two xy vectors?

texts:
I have some code that returns the x and y linear velocities of a moving space ship. How can I combine these to give me total speed?

x = self.player._box2dBody.GetLinearVelocity().x;
y = self.player._box2dBody.GetLinearVelocity().y;

So if:
x = 1.99
y = -1.63

How do I calculate the total speed?


texts: Is ruby a suitable language for game development?

texts: I want to move into some game development, but the only language I know really well is Ruby. Most of what I have read seems to point towards lower level languages like C++ for game development, or languages for specific frameworks like C# for using XNA. Does anyone have any experience using a language like ruby for game development? If so, would you advise for or against it?


texts:
Having some experience of XNA but none of 3D programming. I have an idea i want to realize but i have not decided to do it in 3d or 2d. Im not sure which one will be best in XNA.

I want to have a shape like a blob that can reshape depending on input. The morphing does not need to be very advanced. It could be a circle (2d) or globe (3d) that just has one point that moves slightly in a random direction.

In ASP.NET i have made this through the 2d Draw classes where i can make lines, circles, squares etc and then modify the points that makes them up. But it seems to me that XNA does not have classes for making 2d shapes (can i get this confirmed?). If it had, then this would be the quickest solution for me.


texts: Why is the Hiero font not coordinated to fit neatly in the display window?

texts:
I imported a font with Hiero and I draw the font like:

font.draw(batch, "1", 0, 48);

This is the resultant image:

So the font it moved up to hit the bottom perfectly, but it doesn't touch the left side perfectly. Why does this happen? Is there a way I can fix this? It seems like if I set the x coordinate to -3 it works, but this seems somewhat arbitrary. Any ideas?


texts: App using LWJGL can't find display mode extension on Linux

texts:
I'm running LWJGL app on Ubuntu virtual machine with no phisical graphic card. I set up Xvfb and Mesa3D but it fails with exception

java.lang.ExceptionInInitializerError: null
        at org.lwjgl.opengl.Pbuffer.createPbuffer(Pbuffer.java:234) ~[lwjgl.jar:na]
        at org.lwjgl.opengl.Pbuffer.<init>(Pbuffer.java:219) ~[lwjgl.jar:na]
        at org.lwjgl.opengl.Pbuffer.<init>(Pbuffer.java:190) ~[lwjgl.jar:na]
...
Caused by: java.lang.RuntimeException: org.lwjgl.LWJGLException: No display mode extension is available
        at org.lwjgl.opengl.Display.<clinit>(Display.java:141) ~[lwjgl.jar:na]
        ... 7 common frames omitted
Caused by: org.lwjgl.LWJGLException: No display mode extension is available
        at org.lwjgl.opengl.LinuxDisplay.init(LinuxDisplay.java:724) ~[lwjgl.jar:na]
        at org.lwjgl.opengl.Display.<clinit>(Display.java:138) ~[lwjgl.jar:na]

App is running from cron using script

export DISPLAY=localhost:1.0
export XAUTHORITY=/home/ubuntu/.Xauthority
xauth add localhost:1 . 11111111111111111111111111111111
Xvfb :1 -screen 0 1024x768x16 -nolisten tcp
/home/username/start.sh

Most of steps above were adopted from here but I'm not sure I did it correctly.
Any help would be appreciated!


texts: Why does Unity use reflection to get the update method?

texts:
Why does Unity use reflection in order to access MonoBehaviour message methods like Awake, Update, Start,...?

Wouldn't it be slow to use reflection? Why doesn't it leverage other approaches like Template Method? It could simply define the methods as abstract in MonoBehaviour base class and force the subclasses to implement it.


texts:
I made a Java program which generates a random map based on Perlin Noise + Poisson Algorithm + Voronoi Diagram. Here you can see a generated map. White are caves, black is empty.

The problem is that my character will go through this caves so I need to zoom this image to see only a big piece of where I am. But when I zoom in, the image obviously gets pixelated and looks really bad. So I save it as an svg image and the quality now is perfect but as far as I have read svg images are slow to render and 2D Games Engine (like SFML, SDL) can't render them.

The approach I have read about is that maps are tiled based, a tile size depending on zoom level, but this is a randomly generated map and zooming in svg image to generate the tiles and save the tiles to formats like png, jpeg, would be very slow (Or I am wrong?).

What can I do here? I have searched how to zoom the Perlin Noise function but it isn't a fractal noise so I can't.

Thank you in advance for your help! I am new in game development!


texts: Unity directional light for a day night cycle on a hex sphere

texts:
So I am trying to create a Day Night cycle on a sphere but it doesn't work the way I want it to.
As the model is hex tiled, you see the edges of the hex tiles also lit up like below. I am using a directional light source for the same.

I don't want the above effect. I want it to ignore the edges and just be a straight line instead. Something like below

Is there a way inside Unity that I could achieve this effect just using the lights?


texts: Is it acceptable to use Hash Maps for input, copying one hash map to an another during the game loop?

texts:
I recently started developing a simple 2D game in Java using JavaFX and no proper game library (libgdx etc.) and among the things I did was to make an InputManager to handle every input from the player.

In the InputManager I'm using a Hash Map, called inputMap, using a String as the key and a Boolean as the value. When the player presses a movement key, e.g. the UP arrow key, InputManager sets the value of the "UP" key of the map to "true". The game loop which also has a Hash Map, copies the map from the InputManager (via a getInputMap() method) to it's own map every frame and then using if statements the player moves.

My questions is, is this an acceptable way of doing this? The movement and every action in general.

Is there a better way of doing it without the use of Hash Maps or if Hash Maps are the way to go is there a better, more appropriate, way to implement them?

Below is the InputManager class:

class InputManager {

    private Scene scene;
    private Map<String, Boolean> inputMap = new HashMap<String, Boolean>();

    InputManager(Scene scene) {
        this.scene = scene;
        populateInputMap();
        getInput();
    }

    private void populateInputMap() {
        inputMap.put("UP", false);
        inputMap.put("DOWN", false);
        inputMap.put("LEFT", false);
        inputMap.put("RIGHT", false);
        inputMap.put("RESTART", false);
    }

    private void getInput() {

        scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {

                if (event.getCode() == KeyCode.UP) {
                    inputMap.put("UP", true);
                }
                if (event.getCode() == KeyCode.DOWN) {
                    inputMap.put("DOWN", true);
                }
                if (event.getCode() == KeyCode.LEFT) {
                    inputMap.put("LEFT", true);
                }
                if (event.getCode() == KeyCode.RIGHT) {
                    inputMap.put("RIGHT", true);
                }
                if (event.getCode() == KeyCode.R) {
                    System.out.println("RESTART");
                }
            }
        });

        scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.UP) {
                    inputMap.put("UP", false);
                }
                if (event.getCode() == KeyCode.DOWN) {
                    inputMap.put("DOWN", false);
                }
                if (event.getCode() == KeyCode.LEFT) {
                    inputMap.put("LEFT", false);
                }
                if (event.getCode() == KeyCode.RIGHT) {
                    inputMap.put("RIGHT", false);
                }
            }
        });
    }

    public Map getInputMap() {
        return inputMap;
    }
}

And this is the part of the Game Loop that the map gets copied:

private void updateGame() {
    frameCount++;
    inputMap.putAll(inputManager.getInputMap());

    if (inputMap.get("UP").booleanValue()) {
        y -= 5;
        player.setLayoutY(y);
    }

    if (inputMap.get("DOWN").booleanValue()) {
        y += 5;
        player.setLayoutY(y);
    }

    if (inputMap.get("LEFT").booleanValue()) {
        x -= 5;
        player.setLayoutX(x);
    }

    if (inputMap.get("RIGHT").booleanValue()) {
        x += 5;
        player.setLayoutX(x);
    }
    inputMap.clear();
}

I am aware that the movement part is not right.


texts: Portable sound and music for XNA / MonoGame?

texts: What is the best (recommended) way to integrate audio (both sound effect and music) in a game project (using C#/XNA) targeting multiple desktop platforms (W7, W8 Metro, Linux, OSX, ...) via MonoGame. XACT was the usual way in XNA but it is deprecated in W8 and also cannot be used with MonoGame, I am looking for an alternaive. Is there one?


texts: So I red an article on "The sound effect" website about recording the audio of a vehicle. I'm planning on making a race game in the future and I'm having a little concern about the sound of the vehicles and I want to ask is what if you have not seen the car for lamboghini veneno in your life let alone record it. How do you go with it?


texts:
I've been working on a small game, and I've been stuck on the collision part. During the collision, when my player hits a block, he stops just as it should, but it then doesn't allow me to another direction (ex: the collision happens on the y axis, it won't allow me to move along the x axis). What I want is to be able to move along the wall while still moving into it (If you know what I mean). I've checked here and here, but they aren't what I'm looking for.

EDIT: The new code allows me to move along the axis's fine, but I'm getting some different problems (shown in pictures)

This is the NEW code for my collision detection:

if(key[KEY_A])
{
    if(tileMap[(x/zoomLevel)-1][y/zoomLevel] < 1 && tileMap[(x/zoomLevel)-1][(y/zoomLevel)+1] < 1)
    {
        if(tileMap[((x/zoomLevel)+1)][y/zoomLevel] < 1 && tileMap[((x/zoomLevel)+1)][(y/zoomLevel)+1] < 1)
        {
            x-=moveSpeed;
            dirX = 0;
        }
    }
}
else if(key[KEY_D])
{
    if(tileMap[(x/zoomLevel)+1][y/zoomLevel] < 1 && tileMap[(x/zoomLevel)+1][(y/zoomLevel)+1] < 1)
    {
        x+=moveSpeed;
        dirX = 1;
    }
}

if(jumping == false)
{
    if(tileMap[(x/zoomLevel)][(y/zoomLevel)+2] < 1)
    {
        y+=gravSpeed;
        gravSpeed*1.2;
        dirY = 1;
    }
}
else
{
    if(tileMap[(x/zoomLevel)][(y/zoomLevel)-1] < 1)
    {
        gravSpeed = 4;
        y-=gravSpeed;
        dirY = 0;
    }
}

Thanks to anyone who can help me with my problem!

And here are some picture based on the new collision:

Falling on ground:

Moving to the left when on top of a block:

Moving to the left:

Jumping when moving right:


texts: Need some help implementing VBO's with Frustum Culling

texts:
i'm currently developing my first 3D game for a school project, the game world is completely inspired by minecraft (world completely made out of cubes). I'm currently seeking to improve the performance trying to implement vertex buffer objects but i'm stuck, i already have this methods implemented: Frustum culling, only drawing exposed faces and distance culling but i have the following doubts:

I currently have about 2^24 cubes in my world, divided in 1024 chunks of 16*16*64 cubes, right now i'm doing immediate mode rendering, which works well with frustum culling, if i implement one VBO per chunk, do i have to update that VBO each time i move the camera (to update the frustum)? is there a performance hit with this?
Can i dynamically change the size of each VBO? of do i have to make each one the biggest possible size (the chunk completely filled with objects)?.
Would i have to keep each visited chunk in memory or could i efficiently remove that VBO and recreated it when needed?.


texts: C++ OpenGL wireframe cube rendering blank

texts:
I'm just trying to draw a bunch of lines that make up a "cube". I can't for the life of me figure out why this is producing a black screen. The debugger does not break at any point.

I'm sure it's a problem with my pointers, as I'm only decent at them in regular c++ and in OpenGL it gets even worse.

const char* vertexSource =
    "#version 150\n"
    "in vec3 position;"
    "void main() {"
    "   gl_Position = vec4(position, 1.0);"
    "}";

const char* fragmentSource =
    "#version 150\n"
    "out vec4 outColor;"
    "void main() {"
    "   outColor = vec4(1.0, 1.0, 1.0, 1.0);"
    "}";

int main() {

    initializeGLFW();

    // Initialize GLEW
    glewExperimental = GL_TRUE;
    glewInit();

    // Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    // Create a Vertex Buffer Object and copy the vertex data to it
    GLuint vbo;
    glGenBuffers( 1, &vbo );

    float vertices[] = {
         1.0f,  1.0f,  1.0f, // Vertex 0 (X, Y, Z)
        -1.0f,  1.0f,  1.0f, // Vertex 1 (X, Y, Z)
        -1.0f, -1.0f,  1.0f, // Vertex 2 (X, Y, Z)
         1.0f, -1.0f,  1.0f, // Vertex 3 (X, Y, Z)
         1.0f,  1.0f, -1.0f, // Vertex 4 (X, Y, Z)
        -1.0f,  1.0f, -1.0f, // Vertex 5 (X, Y, Z)
        -1.0f, -1.0f, -1.0f, // Vertex 6 (X, Y, Z)
         1.0f, -1.0f, -1.0f  // Vertex 7 (X, Y, Z)
    };

    GLuint indices[] = {
        0, 1,
        1, 2,
        2, 3,
        3, 0,
        4, 5,
        5, 6,
        6, 7,
        7, 4,
        0, 4,
        1, 5,
        2, 6,
        3, 7
    };

    glBindBuffer( GL_ARRAY_BUFFER, vbo );
    glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW );
    //glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vbo);
    //glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( indices ), indices, GL_STATIC_DRAW );

    // Create and compile the vertex shader
    GLuint vertexShader = glCreateShader( GL_VERTEX_SHADER );
    glShaderSource( vertexShader, 1, &vertexSource, NULL );
    glCompileShader( vertexShader );

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader( GL_FRAGMENT_SHADER );
    glShaderSource( fragmentShader, 1, &fragmentSource, NULL );
    glCompileShader( fragmentShader );

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader( shaderProgram, vertexShader );
    glAttachShader( shaderProgram, fragmentShader );
    glBindFragDataLocation( shaderProgram, 0, "outColor" );
    glLinkProgram (shaderProgram);
    glUseProgram( shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation( shaderProgram, "position" );
    glEnableVertexAttribArray( posAttrib );
    glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0 );

    // Main loop
    while(glfwGetWindowParam(GLFW_OPENED)) {

        // Clear the screen to black
        glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
        glClear( GL_COLOR_BUFFER_BIT );

        // Draw lines from 2 vertices
        glDrawElements(GL_LINES, sizeof(indices), GL_UNSIGNED_INT, indices );

        // Swap buffers
        glfwSwapBuffers();
    }

    // Clean up
    glDeleteProgram( shaderProgram );
    glDeleteShader( fragmentShader );
    glDeleteShader( vertexShader );

    //glDeleteBuffers( 1, &ebo );
    glDeleteBuffers( 1, &vbo );

    glDeleteVertexArrays( 1, &vao );

    glfwTerminate();
    exit( EXIT_SUCCESS );
}


texts: How do I programmatically change the areaSize variable of an Area Light object in Unity?

texts:
I'm trying to change the areaSize property of an Area Light object, but it looks like it isn't exposed in the class, itself.

this.light.areaSize =
    new Vector2(this.areaLightWidthSlider.Value, this.areaLightHeightSlider.Value);

This code results in the error:

  error CS1061: 'UnityEngine.Light' does not contain a definition for 'areaSize' and no extension method 'areaSize' accepting a first argument of type 'UnityEngine.Light' could be found (are you missing a using directive or an assembly reference?)

The documentation  says it exists, as an "editor only" property.

Is there any way to programmatically access and change this property, possibly using reflection or serialized properties?

I am using Unity 4.6, if at all relevant.


texts: How to set indent spacing of a tree in libGDX scene2d?

texts:
I've been trying to create a customized UI using scene2d library in libGDX. However I am having troubles as I'm trying to set a custom indent spacing on my Tree object.

I have tried to search for the answer but haven't actually found any discussions about this on the internet.

This is the current situation which I am having.

This is how I would prefer it to look like.

All I want is that I could be able to change the size of the margin which is caused by nodes being on different levels. How can I achieve this?


texts: Adding an existing script to a gameobject programmatically

texts:
Is there a way to take a script and apply that specific script to an object through code?
In pseudocode, what I'm trying to do is essentially as follows:

ObjectOne.MyScript = ObjectTwo.GetComponent<MyScript>();

The closest thing I've found to doing this is AddComponent(), but that only takes either a string or a type and I'd assume it just finds the relavant script and instantiates a clean copy of it. That could work for what I want to do as I could just fill in the relevant information, but that would be tiresome and there should be an easier way to do this.


texts: Why does matrix multiplication lead to different result if it's done on CPU, compared to GPU(shader)?

texts:
If I'm calculating a "camera space" on the CPU, by multiplying the view with the projection matrix on the CPU , and afterwards multiplying the world to the result my vertices do not pass to the pixel shader (probably because they are thrown of the screen space).

On the other hand if I'm multiplying the world with the view and the result with the projection, all on the GPU the result is right.

What exactly happens on the GPU that doesn't happen when multiplying on the CPU?


texts:
I have been designing a simple turn based Civ-like game over the last two days with libGDX to test myself.  I have a units class that can be extended to make unit types and I have my game board set up.  Everything is almost done... except for the AI, specifically the unit AI.  I want to collect all active units into two seperate arrays (the libGDX array), one for the human player and one for the AI units.  I will not be using diplomacy for the sake of simplicity.

I first tried Array<Unit> playerUnits = new Array<Units>(); and calling the playerUnits.get(index) method to return the unit.  My thought process seems to not be logical, though, as I found there was no way to get the x and y coordinates of units that do not yet exist (all units have to be built in factories in game).  Next, I tried to store x and y coords in an XYCoords method, however there was no built in way to add units to the array later.

I have my pathfinder implemented (with a few minor bugs that cause units to flicker once moved) and now need to simply add the reaction to units.  I have no idea how to do this and as you have probably guessed by now I have never had to implement a more complex AI than one that follows the player mindlessly.  Has anyone had a similar problem that could somehow help me?


texts:
I am creating a game using the new Data-Oriented Tech Stack (DOTS).
I am using Entities with the PhysicsShape and PhysicsBody authoring components of the new Physics package. Some of my PhysicsShape have "Collison Response: Collide Raise Collision Events" set. Unfortunately the documentation of the new Physics system doesn't say anything about how I can detect and handle these collision events, and information on the Internet regarding this is very sparse and disorganized. How can I detect when one PhysicsShape collides with another one sending collision messages and run some code in that case?


texts: line segment triangular-prism intersection

texts:
What is the best way how to perform intersection test between triangular-prism (used as bounding "box") and line-segment (NOT ray)? The triangular prism is not axis-aligned and it is stored as a triangle (3x 3D coordinates) and the height of the triangle?

If you advise me some "mathematicaly" optimalized solution (not just simple geometric but something like Moller-Trumbore for simple triangle) I will be grateful. I don't need the distance, just bool value (intersect/not intersect).


texts: What is the correct way to draw layered Sprites in modern OpenGL?

texts:
So what do I mean by layered sprites? Layered Sprites are Sprites that consist of multiple layers, e.g. you have sprite sheets for the basic Body, the Head, Clothes, Weapons, etc.

Well now I wanted to know how you would draw this in the most efficient way; right now the idea is to use vertex buffer objects (VBOs), but I heard that it is expensive to change the textures in a VBO...

So what would be the correct way to draw them? My idea right now would be to draw the Map tiles first (with a texture atlas), then I would draw all the basic bodys, then the heads, then clothes, and then the weapons. Would that be the best way or is there a more efficient way?

I also thought of using vertex arrays instead of VBOs, but as far as I know they are deprecated...


texts: In Unity, Change which mouse button is used to scroll in ScrollRect

texts:
I've created a new ScrollView in Unity. How do I change which mouse button is used to scroll in ScrollRect (through script or in the editor).

By default it's the left mouse button. I'd like to be able to change this to another mouse button.

I'd also like to be able to use a keyboard key and disable it altogether (via script without also disabling the scrollbars), but mainly I at least want to change it from the left mouse button.


texts:
I want to generate mipmaps for 2D textures as an offline step. My priority is for image quality, execution time is not a concern. The images will, naturally, always be halved and will always be powers-of-2.

I've found this fine article on the subject, which was helpful, but I don't have much knowledge on filtering, so I'm not very sure where to start.

I'm looking for algorithms and hopefully some sample implementations that I can base myself on. Also, using a third party library is an option, as long as it is open source and portable C or C++.

Any help is appreciated.


texts: Vulkan Error: cmd buffer submit cant use image because of layout

texts:
I've been coding a Vulkan rendering engine for the past few weeks.
My code still continues to execute and I get the desired output, but I am getting an error.

I'm fairly certain that my error is a mistake in my code somewhere. My code is 1000+ lines, so I'm not going to ask anyone to debug it. I guess my question is what typically causes the error I'm getting, and how can I fix it?

I've been pretty closely following this (if this helps anyone): https://software.intel.com/en-us/articles/api-without-secrets-introduction-to-vulkan-part-3#_Toc445674490

My code draws the desired triangle from the tutorial, but I get an error for the first 3 frames:

VKDBG: ERROR: @[DS]: Cannot submit cmd buffer using image (0x6) [sub-resource: aspectMask 0x1 array layer 0, mip level 0], with layout VK_IMAGE_LAYOUT_UNDEFINED when first use is VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.
VKDBG: ERROR: @[DS]: Cannot submit cmd buffer using image (0x7) [sub-resource: aspectMask 0x1 array layer 0, mip level 0], with layout VK_IMAGE_LAYOUT_UNDEFINED when first use is VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.
VKDBG: ERROR: @[DS]: Cannot submit cmd buffer using image (0x8) [sub-resource: aspectMask 0x1 array layer 0, mip level 0], with layout VK_IMAGE_LAYOUT_UNDEFINED when first use is VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.

I suppose I could just ignore this, because I get a desired output and the error doesn't seem to break anything, but I would guess that it's bad practice to leave this unfixed.

Thank you for anyone helping!


texts: How to achieve light effect on a car panel icons?

texts:
I'm making a car and I want to make lightable icons on its panel. I want to add 'on' and 'off' effect to them separately. The Sprites are plane objects, with one material and UV texture for each plane.

If I change material property - it will change in all objects which use this material. I don't think creating 10 materials for 10 sprites is the best choice, what should I do in this situation?


texts: Why wouldn't one use Canvas for HTML 5 game development?

texts:
I'm just getting into the HTML 5 game development. I've discovered that some games seem to be created using just JS/CSS/HTML instead of the canvas.

Since canvas seems to enjoy good browser compatibility (http://caniuse.com/#feat=canvas), I'm wondering why someone wouldn't use it?


texts: How do I program a fan in a platformer game?

texts:
Fan physics

I have a platformer game and want to have fans in it that blow in a given direction and if the player presses the jump button they can go even further.

How do I do this?

side note:

I am working with godot engine

EDIT

My character moves on the two axes using two variables, both multiplied by speed: move_dir and y_velo. gravity affects y_velo and the arrow keys affect move_dir


texts: Blender: projecting an image via a spotlight onto a plane

texts:
I've create a plane with a spot light shining from above onto it. The spot light projects a texture of an image onto the plane. The light shots out at an angle but the texture is projecting in a flat 2d form on the plane.

I expected it to stretch out much like the advertisements you'd see drawn on the pitch during a rugby or cricket match. Any idea how I'd change the way the image is shawn onto the plane?

The image should stretch out with the nearer section looking a bit more narrow than the top far section.


texts: Is there a HTML/JS game engine/library that deals with things (HUD, menus, accounts, etc) other than the core gameplay?

texts:
I've been looking through the many HTML/Javascript game engines/libraries out there (many of which are found here https://github.com/bebraw/jswiki/wiki/Game-Engines).  Most of them seem fairly focussed on the actual gameplay components: sounds, sprites & graphics management, doing 2D and 3D animations, collision detection, etc.

From what I can see most of them lack things to handle all the other stuff that goes into a web game such as menus, HUD, workflows of all the various scenes, management of various points/achievements and understanding of how level progression works with that, integration with Facebook or other external accounts, etc.

Does anything exist that adresses these sorts of pieces?  I realize none of them are that difficult to achieve on their own but it would seem to be somewhat distracting overhead that gets in the way of the main game development focus, and is usually very similar from game to game.

Additional question: would something like this be useful, would you want/use it?


texts: Can a loading screen be implemented using one thread only? If so, how?

texts:
I have seen guides on how to implement a loading screen using more than one thread. But sure it must be possible to do so with one thread, since older (even 2D) games that run on single-threaded machines had loading screens as well.

So, how do you do it?


texts: How to draw a Sprite with Touch Points in LibGDX

texts:
I want to draw some path with user's touch. if users moves finger from one position to another position a path will be drawn exactly as user moved finger.

We can draw a line with by defining color but i want to draw that line with sprite. i want to use image for that. is it possible with LibGDX? if yes , how we do that? and how will i generate image to use as sprite for that?


texts: Procedurally splitting and merging paths

texts:
I'm making a text-based adventure which sends the player along different paths depending on their choices.  Each scene is like a node in a directed graph. Each node has a time step which is equal to the number of nodes prior + 1.  There is a maximum of Tn nodes per time step, say 5, and so you can visualise this in this way:

I want to generate paths like these.

Where a node points to more than one other, that could be called a fork and where two point to one, that could be called a merge.

At any particular timestep there will tend to be Tn / 2 paths, only rarely going down to one or up to Tn.

Does anyone have ideas or know of any similar work?

(One small issue - paths never cross - that is, those on the left stay on the left until merging to the right.  And there's no wrapping from far left to far right.  Because of this, it seems like nodes on the far left or far right of a timestep will have a smaller probability of merging.  Is this avoidable?)


texts:
I'm having trouble drawing a particle effect between two actors in UDK - Both the source and the target are not static objects, so as far as I can tell I need to do it in the code not in kismet. Here's what I've got at the moment and it seems to not be doing anything at all. Ideas?

BeamEmitter[0] = new(self) class'UTParticleSystemComponent';
BeamEmitter[0].SetAbsolute(false, false, false);
BeamEmitter[0].SetTemplate(BeamTemplate[0]);

BeamEmitter[0].SetTickGroup(TG_PostUpdateWork);
BeamEmitter[0].bUpdateComponentInTick = true;
self.AttachComponent(BeamEmitter[0]);
BeamEmitter[0].SetBeamEndPoint(2, tarPos);
BeamEmitter[0].ActivateSystem();


texts: Push and damage player pawn when hit by rotating pawn? (UDK)

texts:
I'm working on a game in which the player runs around a level themed as a pinball machine.  There are flippers that react to the presence of pinballs by flipping (as one would expect pinball flippers to do).  The problem that I'm having is that if the player is in the path of the flipper as it rotates, the player is instantly killed.  The desired behavior is that the player is damaged and pushed away from the moving flipper.

I've tried all sorts of things to make this stop happening.  Currently, in the flipper, I have the following code to handle the collision:

event Bump(Actor other, PrimitiveComponent otherComp, Object.Vector hitNormal)
{
    local vector pushVelocity;

    if(/*If Flipper is moving and is bump()ing the Player*/)
    {
        pushVelocity = hitNormal * CalcLinearVelocity(vsize(location - other.location));
        player.TakeDamage(playerDamage, none, player.Location, pushVelocity * 2.1f, class'DamageType', , self);
    }
}

By using all sorts of logging, I can determine that the code in question is being called when the flipper hits the player and the player is being killed on the first frame this collision occurs--logging within the if() block only appears once.  And yes, playerDamage is a value low enough that it would take many hits to kill the player.

Does anyone have any insight as to why the player is immediately dying instead of being damaged and pushed away?  Or what sorts of things I should try to get my intended behavior?


texts: How should I handling clipping vertices that are closer to the eye than the near clip plane?

texts:
I'm rolling my own 3D engine, in JavaScript, and using only canvas drawing, no WebGL. This is another Minecraft clone; I love boxes, don't judge me.

So far, everything works wonderfully, except for one thing: in 3D, when some vertices go behind the near clipping plane, their projection on the screen comes out weird (assuming other vertices used to trace a plane are in front).

I tried clipping these points but then I can see trough the surfaces that use these vertices. In WebGL/OpenGL the graphics card takes care of these points and the plane is rendered correctly, but I don't have access to hardware so I must code this myself.

I'm not quite sure what to make of it, currently the last thing that came to mind is to reverse the projection of points behind the player's near clipping plane, which seems logical since I must project a point to a screen which is in front of the vertex.

Here are my thoughts:

Here are some images to illustrate what happens:

From distance the blue box renders perfectly well.

When some of the vertices go behind the player's near clipping plane I do reverse projection, but it doesn't look right:

focalLength *= -1;
2d.x = x*focalLength/z;
2d.y = y*focalLength/z;

Note that the gray box behind is completely removed since all the vertices used to draw its faces are behind the player.

This is what happens when look up or down.

I don't know what to make of the math behind this, I'm hoping somebody has encountered the same problem already and can help me.


texts:
I'm using the following code to rotate my object using mouse, for aiming direction. The only problem with this is that it only rotates between 0 to 180 and not full 360 degrees. Can any help me locate the problem?

void Update()
{
  var pos = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);
  var dir = (Input.mousePosition - pos).normalized;
  var angle = (Mathf.Atan2(dir.z, dir.x) * Mathf.Rad2Deg + 270) % 360;
  this.gameObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.down);

  if (Input.GetMouseButtonDown(0))
  {
    GetComponent<Rigidbody>().AddForce(dir.x * Force, 0, dir.y * Force, ForceMode.Impulse);
}


texts: Efficient path-finding on 2D tile-based multilevel map

texts:
It's a question I've been thinking about for some time... How do you effiently find a path on a 2D tile-based multilevel map? The map I use, for example, is 2048 on 2048 tiles wide. It has 14 levels and levels are connected by stairs, ladders, rope holes, ...

How would you introduce level-changing tiles into A* in an efficient way? I know it is possible to add multilevel path-finding by just adding edges from an up-node to the corresponding down-node. But then path-finding isn't very efficient.

For example. What if the current node (e.g. [100, 100, 7]) is directly under the goal (i.e. [100, 100, 8]), and we can't go up anywhere near the current node. Instead we first have to go down some levels, and then up again, only then to reach the goal. A lot non-existing paths will be considered (= a lot of time and computation) before we finally find an existing path.

Feedback appreciated,
Gillis


texts: How can I make a chronometer for an HL2: EP2 Mod?

texts:
I'm trying to make a chronometer for a mod I created. I looked on the web, but there are only countdown timers for TF2, nothing for HL2: EP2. In my case, it is an absolute necessity to use HL2: EP2.

The idea is: the player runs through a trigger, the chronometer starts, and at the end of the level, the time elapsed to complete it is displayed. I am using Hammer Editor.

Firstly, it is not necessary that the time is displayed on HUD.
I want to be able to count the time elapsed between a trigger enabling it and another input stopping it.

I've taken a close look to logic_timer and to math_counter, but I don't know how to retrieve the time elapsed since the logic_timer activated the math_counter, neither how to display it on screen.

I managed to fire an output from the logic_timer each second, and that it increases the math_counter, but I am unable to retrieve the value of the math_counter. I've also taken close looks to the OutValue and OnGetValue outputs (math_counter) but nothinng is telling how to get its value...

Finally, I followed Customizable triggered HUD-message tutorial, and I can see it in Hammer Editor, but the Output that was added is not working. This tutorial explains how to have displayed HUD message coming from inputs instead of several game_text. When I use it on my map, nothing happens.


texts: How does Lumberyard stack up against Unity 5 and UE4?

texts:
Amazon released a new game engine called Lumberyard today.

How does it compare to the other two major 3D game engines, Unity and Unreal Engine? What advantages and disadvantages does it have? What can it do that the other two can't do, and vice versa?


texts:
I try to learn Scala the fun way, with a little libgdx project.

Now I'm somewhat stuck:

val go = new TextButton("Go", style)
go.addListener(new ClickListener()
{
   override def isPressed() : Boolean =
   {
     Predef.println("isPressed!)
     true
   }
}

This doesn't work, sadly. Not sure why. I tried returning a "java.lang.Boolean" but the compiler doesn't allow for that, saying these would be incompatible types.

On the other hand, the "void"-method of keyTyped works like a charm:

textField.setTextFieldListener(new TextFieldListener()
{
  override def keyTyped(textField: TextField, key: Char)
  {
    textFieldInput = textField.getText()
    Predef.println(textFieldInput) // TODO remove
  }
});

Here when I type something it gets printed to the console.

Any ideas?

That's probably not really related to game-development, still I wasn't sure if another forum would've been a safer bet.


texts: How to create axes for a console controller

texts: What should I change in the input manager to enable me to use a joystick? I have a usb cable to connect the joystick to the computer but how do I set up the controls?


texts: Accessing variables defined in another .js file in rpgmaker MV

texts:
I'm coming from C++, diving into JS and enjoying the journey so far but I've been at an en passe for the past 2 days and I'm exhausted.

I need help figuring out how to access variables across plugins.

I tried following the guidance in this posting (and numerous others stating to follow the same syntax): https://forums.rpgmakerweb.com/index.php?threads/mv-syntax-for-variables-in-script-calls.48422/

I set these values in plugin1.js:

var weaponRight = 0;
var weaponHeight = 0;

var a = weaponRight;
var b = weaponHeight;

$gameVariables.setValue(5, a);
$gameVariables.setValue(6, b);

Then try to access them in this script:

var z1 = eval($gameVariables[5]);
var z2 = eval($gameVariables[6]);
...
this.x += (z1 || 0);
...

if I just enter an int, say 5--in place of z1--the transform executes.
In addition, I emulated the parsing logic in the first JS file to the 't', so I'm certain the error is coming from my ignorance.


texts: Using Google App Engine to Perform World Updates vs an Authoritative Server

texts:
I am considering different game server architectures that use GAE.  The types of games I am considering are turn-based where the world status would need to be updated about once per minute.

I am looking for an answer that persuades me to either perform the world update on the google servers OR an authoritative server that syncs with the datastore.  The main goal here would be to minimize GAE daily quotas.

For some rough numbers, I am assuming 10,000 entities requiring updates.  Each entity update would require:

Reading 5 private entity variables (fetched from datastore)
Fetching as many as 20 static variables (from datastore or persisted in server memory)
Writing 5 entity variables

Clients of the game would authenticate and set state directly against GAE as well as pull the latest world state from GAE.

Running the update on GAE would consist of a cron job launched every minute.  This would update all of the entities and save the results to the datastore.  This would be more CPU intensive for GAE.

Running the update on an authoritative server would consist of fetching entity data from the GAE datastore, calculating the new entity states and pushing the new state variables  back to the datastore.  This would be more bandwidth intensive for the datastore.


texts: How do I replicate the warp effect from Geometry Wars?

texts:
I'm trying to achieve the warp effect that you see in games like Geometry Wars.

Can someone help explain what is going on here? I feel like the grid's z axis is manipulated in some way, any way, by the programmer, but is there maybe some known mathematical equation to really get the correct warping effect?

Edit: To be more specific, I mean the warping of the grid. How everything looks pulled towards the negative z axis and then bounces.


texts: How can I deal with different states in a multiplayer game?

texts:
I'm currently just making a concept for a MMORPG-like (much less massive) game, in which the player can do all the usual stuff (farming, talk to NPCs, accept quests, kill monsters etc.). An important aspect is, that as an MMORPG you can see the other players walking around in the world, and taking care of their business. Although most of the smaller quests aren't much of an issue, I also want to have a few bigger quests which would contain more story, simple cutscenes and might even have an impact on the world. And this is where it gets problematic, because I don't want to spoil a quest to a player who hasen't begun with it yet, but at the same time the first player should generally see other players who have.

An example would be that if you let an important NPC die in a certain quest, it will not appear again for you.
Or in a cave the way is blocked, until you complete some other quest which removes the stones which where in your way.
Maybe it's even just that an NPC will lead you the way to some place, but it should not become inaccessible to other players. That is fine and perfectly doable for a singleplayer-game, but it gets difficult for a multiplayer game.

I can let other NPCs react differently when you let the NPC from the first example die, but I don't really know how to make the game behave when you stand where the dead NPC should be, but he's not there for you.
I've thought about cheking the quest state before the client receives the information that the NPC is there, but that would get really messy very soon. Not showing an NPC is one thing, but having multiple instances of it where one leads the way for player A and one sells items to player B will grow more and more into a readability nightmare for developers.

And it gets even worse when the map changes; did you just see that other player pass through the wall of stones I see here? Someone of the devs really screwed up the player experience and immersion in the story there...

Something else I thought of are (singleplayer-)"instances" which some games use for such areas. But that also won't work for every case (eg. when the changes are permanent), and when you suddenly enter an instance where you wouldn't expect one to be because you haven't progressed far enough in the storyline would confuse me as a player.

Are there any solutions to this? Or will I have to go with NPCs which never leave their position, and a never-changing world?


texts:
I have been making a game like Minecraft or Terraria in which you add blocks and such to the world, and I came across this interesting debacle, the game is in a top down 2D perspective, and I would like to make it so users can add water to the world, however I would also like the water to behave like water would in the real world.

In other words, spread.

I'm guessing the code would work something like

if (space next to water block is open)
{
    \\spread to that block
}

However, this would not stop the water at that point, flooding the underpart of the map and creating little islands where the players have made things.

I could also pre-make the map, and put the water in that way, allowing the land mass of the map to go unscathed, however this prevents the players from making their own rivers and whatnot.

So my question is, do I prevent players from using water? Or do I allow them to and try to fix any disasters?

Would there be any use to code that allows me to limit the amount of water generated?

The reason water is important is due to the fact that several water vehicles are being planned, and water could be used as a resource to feed the player (dehydration etc)

EDIT:
I have worked in water as follows.
It the player will add the water like a block, at this point the water will spread in an equal outward direction.

If the water intersects ANY block it will stop and proceed with phase two, which is to move back and forth to simulate waves.

I found that through using XNA's ability to locate the side of the rectangle intersected, I can make it continue on down a length

For example:

 if (water.Intersects(something) && something.position.Y >= water.Top)
 {
     \\allow the water to continue adding to the width until the width hits something

 }

Here is an image of the partially completed function in action


texts: Vector out of range (Batch rendering & opengl)

texts:
So ive (tried to) implement a batch rendering system, and at the for loop the error pops up and I'm not shure what ive done wrong. Any suggestions to improve the system would be much appreciated. (It's my first time trying to implement this)

#include "masterRenderer.h"

masterRenderer::masterRenderer() {
    quad = vector<Quad>(1000);
    numOf = 0;
}

void masterRenderer::addQuad(Quad quad) {
    masterRenderer::quad[numOf] = quad;
    numOf++;
}

void masterRenderer::init(GLuint shader, string texPath) {
    vector<GLfloat> vertex((3 * 4) * (numOf + 1));
    vector<GLfloat> normals((3 * 4) * (numOf + 1));
    vector<GLfloat> color((3 * 4) * (numOf + 1));
    vector<GLfloat> uv((2 * 4) * (numOf + 1));

    int nv = 0, nn = 0, nc = 0, nu = 0;

    GLfloat sizeV = 0, sizeN = 0, sizeC = 0, sizeUv = 0;

    for (int i = 0; i < numOf; i++) {      // The error seems to pop up over here.
        for (int j = 0; j < 3 * 4; j++) {
            vertex[nv] = quad[i].g_vertex_buffer_data[j];
            sizeV += quad[i].g_vertex_buffer_data[j];
            nv++;
            normals[nn] = quad[i].g_normal_buffer_bata[j];
            sizeN += quad[i].g_normal_buffer_bata[j];
            nn++;
            color[nc] = quad[i].g_color_buffer_data[j];
            sizeC += quad[i].g_color_buffer_data[j];
            nc++;
        }

        for (int j = 0; j < 2 * 4; j++) {
            uv[nc] = quad[i].g_uv_buffer_data[j];
            sizeUv += quad[i].g_uv_buffer_data[j];
            nc++;
        }
    }

    TextureID = glGetUniformLocation(shader, "textureSampler");
    texture_handle = Util::loadTexture("test.png");

    glGenBuffers(1, &normalbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeN), &normals[0], GL_STATIC_DRAW);

    glGenBuffers(1, &colorbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeC), &color[0], GL_STATIC_DRAW);

    glGenBuffers(1, &uvbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeUv), &uv[0], GL_STATIC_DRAW);

    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeV), &vertex[0], GL_STATIC_DRAW);
}

void masterRenderer::draw(glm::mat4 Model, glm::mat4 View, glm::mat4 Projection, GLuint MatrixID) {
    glPushMatrix();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture_handle);
    glUniform1i(TextureID, 0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(2);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(3);
    glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    for (int i = 0; i < numOf + 1; i++) {
        Model = glm::translate(glm::mat4(1.0f), glm::vec3(quad[i - 1].pos.x, quad[i - 1].pos.y, quad[i - 1].pos.z));
        Model = glm::rotate(Model, glm::radians(quad[i-1].yrot), glm::vec3(0.0f, 1.0f, 0.0f));

        glm::mat4 mvp = Projection * View * Model;
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &mvp[0][0]);
        glDrawArrays(GL_QUADS, 4 * i - 1, 4 * i);
    }
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    glPopMatrix();
}

masterRenderer::~masterRenderer() { }


texts:
I'd like to create lights and shadows in a 2D environment, like in the image below:

I did several searches but got no results. Do you have any hint?


texts: I am looking for a word to classify Game Objects (Trees, Rocks, even Bridges) but NOT include Items/Characters

texts:
I am looking for a SPECIFIC definition that includes environmental game objects but NOT other game objects. Trees, Rocks, or even Bridges. NOT items, NOT weapons, NOT Characters, NOT tiles. I'm looking for an answer that is extremely specific for certain entities but NOT most entities.

For my GameObjects, I have them stored as an ObjectType.

typedef enum
{
CHARACTER = 0,   //A PC or NPC
ENVIRONMENT = 1, //A tree, a Rock, a Bridge, a non-animate environmental object
ITEM = 2,        //A sword, bag of gold, pickup-able item
} ObjectType

Obviously, anyone would easily understand that a Character GameObject would be a Character (PC or NPC), and an item would be something like a Sword, bag of Gold, etc.

However, the word "environment" is obviously wrong. I thought of "foliage" to refer to any object that isn't a tile (grass, road, water, a floor) and isn't an item (can pickup, etc.)

Normally, I would call these things 'Objects', because a Tree, a Rock, a Bridge, a Bush, a collection of flowers- these are all objects. However, this is redundantly confusing when GameObjects are referred to as "Objects" and the term 'object' is so common in game engineering.

I couldn't help but think to myself, "There must be a term that is obvious, that I am just not seeing. A word that describes this very common type of game object."

Something that people could easily understand, so I don't have to resort to "EnvironmentObject".


texts: libgdx images go out of proportion on some devices

texts:
I'm trying to develop a simple game using libgdx. The game works perfectly on emulator ( Nexus 5x API 26 x86 ). But when I generated its apk and tested on my phone(Samsung J7), the images somehow seem to go out of proportion.

I dont know if the problem is libgdx-specific or something else is causing the problem. I suspect that the issue is about the different screen sizes or resolution.

This is how I want it to be.

This is how it appears. The images appear to be enlarged.

The app seems to work as expected on larger mobile screens but the images do not scale well to smaller screens.

Does libGdx or the android not automatically resize images according to the hardware being run on ?

Any help would be highly appreciated.

Edit :

boy = new Texture("boyfinal.png");
batch.draw(boy, Gdx.graphics.getWidth()/4 - boy.getWidth()/2, boyY  );


texts: Show path of a body of where it should go after linear impulse is applied

texts:
I am making a game with Andengine and Box2D. I have a dynamic body and I apply linear impulse on the body to move it around when the user have touched the screen.

Now I want to show the path where the body will go when the user have touched. If you have played Angry Birds or Basket Ball Shoot or any other which have projectile motion with a path shown you will get my point. I want to show the white dots which are shown in those games.


texts: How can I simulate a limited (256) color palette in OpenGL?

texts:
On Twitter, I found this screenshot of a game in development:

The image on top seems to be without any color limitation. But the two other pictures at the bottom have a 256 color palette.

I want to achieve a similar effect in my game (I am using OpenGL). How can I do so?


texts:
I have a triangle in the 3D world. I have the:

positions for the three points
the normal vectors for the three points (all the same, because vertices are not shared)

This triangle faces to a direction, so it has a XYZ rotation (but I dont know the rotation itself).

If I put a cube into the same scene, how I can achieve the same rotation for the cube? So if the triangle "looks" upwards, the cube should do the same. If it has a 10f x rotation, how can I get what is the x?


texts: Child transform's position not updated as parent moves

texts:
I have a parent game object Object1. It has a child, which is simply an empty game object called ReferencePoint. ReferencePoint can be any arbitrary point on Object1 itself.

I have another game object Object2. It has a public field called RotationReference, of type Transform. In the inspector, the ReferencePoint on Object1 is assigned to the RotationReference field on  Object2.

As Object1 moves, I expect ReferencePoint to change its position as well. Object2 is supposed to change its rotation to face its RotationReference -- in this case, the ReferencePoint on Object1:

public override void Rotate()
{
    Vector3 relativeRotationReferencePosition =
        this.RotationReference.position - this.transform.position;

    this.transform.rotation = Quaternion.LookRotation(relativeRotationReferencePosition);
}

However, I noticed that Object2 is not rotating at all, even when Object1 is moving. When I step through the call stack multiple times, I discover that this.RotationReference.position always has the same value, even though Object1 is moving.

What am I missing here?


texts: How to make a 'One Hit and Dead' platformer feel fair

texts:
I am currently making a run 'n gun platformer, in which the player dies instantly when they get hit. I'm curious how to make this feel fair. I'm aware of putting checkpoints frequently enough, allowing the player to retry almost instantly, and merciful hitboxes. But I'm curious to know how I should go about level design? Run 'n guns are much different from sanic-speed wall jump platformers like meat boy.

You see, games like Hollow Knight let you learn how to avoid taking hits early in the game by giving easy challenges. If you get hit by something unexpected in Hollow Knight, you can always focus and gain some health, and it wouldn't feel unfair. If that happened in my game, that would feel unfair.

Since I'm designing a Megaman-X like game with a boss at the end of each stage, how am I supposed to go about teaching the player how to dodge fast moving projectiles that you would only know how to dodge after seeing how they act?

And yes, there is going to be a first level before you can go play the other ones in whatever order you like.


texts: Switch statement efficiency in game code

texts:
Recently, I was digging into VVVVVVV's source code that was released on GitHub by Terry Cavanagh. I went into the Game.cpp file, and found that it contains an absolutely gigantic, 3000+ case long switch statement in what is seemingly a function that is called consistently, not just once.
This made me ponder about how efficient switch statements are, and I realized I don't know much about their difference to normal if-else chains. Are switch statements normally used in this manner to implement state handling, and why doesn't something like this lag the game like crazy? (I'm assuming a massive amount of comparisons are being made every time)


texts: Voxel traversal for parabolic projectile arc under constant gravity

texts:
For linear polynomials, there's a bunch of algorithms for efficiently determining which voxels to test for collision (eg. A Fast Voxel Traversal Algorithm for Ray Tracing ). I'm having troubles though, searching for algorithms that work for any other case, such as a parabolic projectile arc under constant gravity.

Are there any algorithms for that case, or am I stuck just trying to sample at a high enough frequency that only rarely will a projectile travel though a wall without getting detected.


texts:
I'm new to CG and I'm building a ray tracer.

I don't quite understand how to set camera parameters and film(pixel plane) parameters.

Say I want to get an image of 400x300 resolution. I can set an fov, and then the distance between the film and camera can be calculated.

If that's true, a high resolution and a "reasonable" fov, e.g 80 degree, will result in a large distance. Does that makes the object small on the final image?

And I feel like people like to determine resolution at first, in order to get an expected image size. To avoid distortion of objects(fish eye), the fov cannot be too large.

So how do I get close look of an object on a high resolution image?

I think the rasterization way is different from ray tracing one since I can project an object into NDC(normalized device coordinate) to make it big, but what about ray tracers?


texts: Strategy for keeping a primitive facing the viewport?

texts:
Using XNA, c#.

I'm writing a stellarium-type of program-- well, trying to :-) -- and I have a 'sun' texture that I'll be pasting onto triangle primitives. I'll also be floating some text above each node, which will probably be on the primitive as well.

My issue is how to force the primitives to always be facing the camera, despite rotations and movements of the viewport. I'm going through my XNA programming books, but there's no obvious solution. I'd appreciate a pointer in the right direction.

Note: I'm not using 3D models, so AFAIK there's no Matrix to work with. I have 3 vector3's that define a triangle, and I guess I have to modify their addresses on each update to face the camera. That seems pretty intensive, so I'm thinking I may be missing something obvious.


texts:
I have a key and door system working, the character(ball) picks up the key and when it is within the collider it sets the text("press E to open") on the screen to active so that they can open the door. This only needs to be there while the door is closed. How Would I fix this. Thank you so much in advance.

    //GameObject E is the canvas text to instruct the player to press E to open the door.
public GameObject E;
//Door is the door itself, I assigned this manually because the door consists of the doorframe and door.
public GameObject Door;
private bool Unlock;
// Use this for initialization
void Start ()
{
    E.SetActive(false);
    Unlock = false;
}

// Update is called once per frame
void Update ()
{
    if (Unlock)
    {
        if (Input.GetKeyDown("e"))
        {
            Door.GetComponent<Animation>().Play();
            E.SetActive(false);
            CodeManager.GotKey = false;
        }
    }
}
void OnTriggerEnter(Collider other)
{
        if (CodeManager.GotKey)
        {
            if(other.gameObject.CompareTag("Player"))
            {
            E.SetActive(true);
            Unlock = true;
            }
        }
}


texts: Implementing axonometric bird-view in XNA

texts:
I made all kinds of logic (waypath, aso) for my strategical game, based on XNA (monogame).
Now I "misused" the Vector2 a little bit:
As I'm working from a "top-down" perspective, I'm using the Y-axis of Vector2 as Z-axis.

My next step is to draw the elements on the screen:
I think the axometric-view called "bird view" would suit the game most.

I spent most time of the weekend searching for a way to achive this, but without any luck.

I know how I would draw the objects and defining the depths, but I have no idea how to "calculate" the top-down-position to the one with the perspective.

Here's a picture of what I want to do:

How do I calculate the "real" position (here on the right-side) to the perspective-view (on the left side)?
From my research I know the key-word is matrix, but that's all I’ve got.

I don't know to define this bird-view, nor how to proper set up the matrix.
I guess with something like Matrix.CreateLookAt?
And if so: Would I have to change all my Vector2s to Vector3, to use the "real" axis, or is there another way I could achive this?

Any help would be greatly appreciated.

Cheers, Richard


texts:
I have been trying to render a "room" with some basic functions and I found some "bugs".

So at first I have made a "room" out of 6 planes in blender and gave each of them a diffrent color.

Afterwards I rendered it using Irrlicht and here is the first resault :

But if I go around the room to see the other sides they start to dissapear:

At first, I though it may be due to the fact that i was "too close" or "too far" from the object, or that the object was "too small" but I have tested all those and got the same resault.

So I guess the problem comes from the way I import and load in the mesh, but I couldn't find a way to solve it.

Here is the code for importing the mesh / rendering it :

IAnimatedMesh* mesh2 = smgr->getMesh("Sky.obj");
ISceneNode* node2 = 0;

if(mesh2)
{
    node2 = smgr->addOctreeSceneNode(mesh2->getMesh(0), 0, -1, 1024);
    //node2 = smgr->addMeshSceneNode(mesh2->getMesh(0));
    node2->setMaterialFlag(EMF_LIGHTING,false);
}

I would like to know why this happens and how to solve it.


texts:
public class TileObject : MonoBehaviour {

////some code was here
public PlayerAnimator playerAnimator;

////some code was here

public void SetTileObject(int xPos, int yPos, TileData tileData)
{
   ////some code was here

    if (tileData.player)
        playerAnimator = new PlayerAnimator();
}

And my question do i lose any performances(or memory) doing this instead of inheritance or something else.(tileObject can be other than player)


texts:
Like the title says I am unable to create EQS assets. I am running 4.25 and there is no option in the BT details panel, nor under "Add assets -> AI". AND there is no option to activate it. Neither under settings or under plugin. Nothing.
What am I doing wrong? See screenshots and thanks in advance


texts: Drawing an arrow using the LineRenderer in unity

texts:
I'm trying to draw an arrow using a LineRenderer in Unity, using the code suggested here.

Based on the UI it all seems good, yet it draws a pin needle, rather than the arrow I would expect from the UI. If I understand the UI right, it should thicken 60% into the line and then become thinner again towards the end.

Any idea what might be going wrong?


texts: Easy road from DisplayObject to Molehill?

texts:
I have a finished Flash game which is rendered using the built-in display tree, i.e. Bitmaps contained in Sprites (and a text here and there, few vector graphics, and one bitmap-filled shape).
For extra performance, I'd like it to use Molehill for rendering, but that's not possible out of the box.

What's the easiest way to make this game use Molehill when available, but fall back to the current method if it's not available?


texts: Unity AddExplosionForce not doing anything

texts:
Recently I've started learning Unity3D. I'm working on a game as an exercise in which you control a space ship and have to dodge asteroids. If you feel like it's getting a bit too much you can hit the space bar, emitting a blast in all directions that repulses nearby asteroids. To create this blast I have the following code:

public class PlayerBlastScript : MonoBehaviour {

public ParticleSystem BlastEffect;

// Update is called once per frame
void Update () {
    if (Input.GetKeyUp(KeyCode.Space)) {
        Fire();
    }
}

public void Fire() {
    ParticleEmitter effect = (ParticleEmitter) Instantiate (BlastEffect, transform.position, Quaternion.identity);
    effect.Emit();

    Vector3 explosionPos = transform.position;
    Collider[] colliders = Physics.OverlapSphere(explosionPos, 25.0f);

    foreach(Collider hit in colliders) {
        if (!hit) {
            continue;
        }

        if (hit.rigidbody) {
            hit.rigidbody.AddExplosionForce(5000.0f, explosionPos, 100.0f);
        }
    }
}
}

Even though the blast effect appears, the asteroids are not affected at all. The asteroids are all rigid bodies so what's the problem?


texts:
I'm creating an RPG game (using C# in Unity API) that uses a leveling system. I went to the Desomos Online Graphing Calculator and created the following curve representing the levels based on experience: https://www.desmos.com/calculator/bsvkba4qg1. Note that the Y-intercept is at approximately (0, 1).

My Character class has the following fields representing the experience curve from above:

public float experience { get; set; }

public int level {
    get
    {
        float level = experience / 120;
        level += 1.123f;
        level = Mathf.Log(level);
        level *= 20;
        return Mathf.FloorToInt(level);
    }
}

However, when the game begins and experience defaults to 0 as floats do, level returns 2. When experience is 100, level returns 13. Clearly there is some error on my part. Have I entered my formula wrong? If so, how can I fix it, and if not, what else might be the problem?


texts: Removing a previously rendered image on a canvas

texts:
I made a platformer using ctx.clearRect and ctx.fillRect, so each time the player moved I would just delete the previous position and draw him again.

Now I'm working on importing my own art into the game and I'm having problems removing the previously drawn image.

Example of some of the code I am using now to render the player:

var playerReady = false;
var playerImage = new Image();
playerImage.onload = function () {
    playerReady = true;
};
playerImage.src = "images/player.png";

var render = function () {
    if (playerReady) {
        ctx.drawImage(playerImage, player.x, player.y);
    }
};

So Im wondering if there is anything similar to ctx.clearRect for ctx.drawImage or what I could do, my current workaround is to render the whole background on top of the previously drawn background + player but this is not ideal for what I´m trying to do.

thank you!


texts: Is there any way in game maker to pass argument parameters to strings executed via the execute_string() function of version 8.0 (pre-studio)?

texts:
Last I checked, the game I'm modding was compiled* using Game Maker 8.0

So for a little set up, here is my situation. There's a game out there which has a box in which you can enter a string and it executes it. I decided to try and mod the game through use of this cheat box along with some other objects which execute strings and whatnot.

In general, this is all essentially powered by the built-in function 'execute_string'. My main problem is that as far as I know one cannot pass arguments to these executed strings, which is essential to anything complicated** I might wish to do.

I know there is a similar function called execute_script which allows for argument parameters to be passed into the code being executed. However, adding scripts as rescources is one of the many things that get "flushed" out of memory when saving/loading using the default save system. I am definitely not interested in reloading code from files on the fly and I don't want to make my own save system (which would still require code to be loaded from files) as I would prefer to basically have to use a save file and a few 3D model/image files to send the mod to anyone else who might be interested in it. I could also send the raw source, but regardless I don't want a lot of unstable resource manipulation.

  So basically, is there a way for me to pass arguments into the code being executed with "execute_string" without having to implement my own function stack memory space and do the pushing and popping of arguments manually?

*The game was made many years ago in game maker 6.0. I believe it was recompiled for efficiency purposes.

**For instance, a very common technique to make some more complicated enemies or buildings is to make your own dynamic memory allocator using an array as a virtual memory space and use the interfaces of raw memory allocation to build lists and trees or whatever else you need. That is definitely something which requires a lot of different function calls.


texts: Which functions does an animation event call?

texts:
I have an animation with animation events in an imported .fbx file. I spent some hours creating  a class with delegates so that I could trigger methods on any C# class I wanted.

Now I wonder if that is necessary? Which types and methods does the animation event delegate a call to? Does it search through all fields, properties, containers etc in the GameObject with the Animator to find matching function names?

I found out unity has released a read-only version of their repository on github so I will dive in there and see if I can find what happens.

Ok I think it looks through all MonoBehavior based off the GetComponents on the GameObject with the Animator.


texts: More realistic currency for spaceship battle game

texts:
This is slightly related to real development but as you know hardest thing to do for developer is naming things. So now I can't figure out what specific currency to use in my spaceship battle game.

Little about game: Space, universe, spaceships, battles. Ships can be destroyed, damaged, repaired, aliens (multi-race) - typical spaceship game. Multiplayer, turn-based, battles not limited to 1 vs 1 - can be different count in both teams (70 vs 45).

Struggle is I want more realistic currency than just credits, gold, crystals etc. Because game currency should be related to battles, repair etc. And maybe (but not mandatory for now) with context to other alien races.

All options is viewed from game character perspective not player.

Requirements:

Something to get after battle (imagine destroyed ship, what to salvage)
Used to repair ship (can be as part of some kind of tool)
Valuable stuff to give someone in distinct part of universe
Space pirates would want to have this stuff

1. Credits (EVE, Elite:Dangerous)

Fictional. No context to game universe at all.

2. Crystals or other minerals (majority of games?)

Game related, fictional value.

This works but if we think in scope of Universe as whole for some aliens this mineral could be worth nothing.

3. Scrap metal (FTL)

Game related , real value.

Best option for now is scrap, scrap metal as you know "FTL" game is using. This works only if we assume all ships in all universe using metal for building spaceships.

It can be used as repair material, it can be found after battle even if ship is empty.

Kinda feel bad to steal this currency from FTL as I love that game :)

4. exotic currencies

Using these would be interesting but need

time - Works great with repairing stuff
information - Great currency to salvage after battle from another ship, but fails to for repairing ship.
more?

Summary

I know there is quite obvious answer but wanted to reach to others and maybe hear something I never though of.

Maybe you can write your pros and cons about every currency i mentioned or point out something where to look?


texts:
I'm currently working on a 2D RPG, where the player character moves on a tilemap but is not constrained to the individual tiles. Every tile in a room is referred to by x and y coordinates to an Array. I'm considering using a Location class to store a float x and float y for the player character, as well as, perhaps, a Room. What are the advantages and disadvantages of this approach versus keeping the float x and float y values of the Player class (thus not creating a Location class)?

Collision detection with walls, objects, and other players will need to be calculated.


texts: Picking 2D objects after transforming camera in XNA

texts:
I have an XNA application (a force based visualisation of some circles) that I've implemented zooming and scrolling in, thanks to this guide.

Before I had the camera implemented, I had picking implemented (click and drag a circle to move it around). However, after the camera transformation I'm struggling to match up my mouse X,Y coordinates with the post-transformation coordinates of my circles.

I attempted to multiply my mouse X,Y vector with my camera transformation matrix. Given a mouse click at (356, 492), after translation I get (713,300), but my objects are around (-1000,900) or so.

So, given a mouse click in local X,Y coordinates and circle locations in post-transformation X,Y coordinates, how do I match them up?

(If it's needed, my VS2010 project is here.)


texts:
I'm making a 2D dungeon crawler. The problem I found, it is that trying to animate the movement through the dungeon it is hard as hell. Then I thought that maybe a 3D dungeon will be better for this, but I don't like it. Are anyways to make a 3D game look like a 2D game? I mean...

There is some kind of shader o camera mode to achieve a 3D game look like this?

(Tough the game is in 3D, looks like it was a 2D game trying to be 3D).


texts:
I know this might be a bit of a noob question, but I can't figure out what I'm doing wrong, and the math that I have done should make this work correctly. I am trying to make a perlin noise map that is normal until a specific range, at which point it would decrease to where all the values trend towards zero, creating an island in an ocean. I am currently generating perlin "sample" values, and then dividing them by a factor which stays close to one up to a specific bound, and then increases polynomialy. The problem however, is that the noise stays stuck in the top right corner, and is darker than I would expect. Here is the mathematical function I am using graphed on Desmos where n is the boundary and x is the distance from the center of the map:

And here is the main body code I am using to generate the noise map:

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

public class GenNoise : MonoBehaviour {

public int width = 256;
public int height = 256;

public float scale = 20f;

public float offsetX;
public float offsetY;

public float falloffRange = 100;
public float falloffPower = 10;

public void RenderNoiseMap()
{
    Renderer renderer = GetComponent<Renderer>();
    renderer.sharedMaterial.mainTexture = GenerateTexture();
}

Texture2D GenerateTexture () {
    Texture2D texture = new Texture2D(width, height);

    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            Color color = GenerateColor(x, y);
            texture.SetPixel(x, y, color);
        }
    }

    texture.Apply();
    return texture;
}

Color GenerateColor(int x, int y)
{
    float xCoord = ((float)x / width * scale) + offsetX;
    float yCoord = ((float)y / height * scale) + offsetY;
    float falloffFactor = FalloffFactor(x, y, width, height);

    float sample = Mathf.PerlinNoise(xCoord, yCoord);
    sample = sample / falloffFactor;
    return new Color(sample, sample, sample);
}

float FalloffFactor(int x, int y, int width, int height)
{
    float falloffFactor = 1;
    float centerX = (float)width / 2;
    float centerY = (float)height / 2;

    float distanceFromCenter = Mathf.Sqrt(Mathf.Pow(2, ((float)x - centerX)) + Mathf.Pow(2, ((float)y - centerY)));
    falloffFactor = Mathf.Pow(2, (Mathf.Pow(falloffPower, (distanceFromCenter / falloffRange)) + 1));

    return falloffFactor;
}
}

And Here is the code that I am using to generate the image in the editor:

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(GenNoise))]
public class NewBehaviourScript : Editor {
public override void OnInspectorGUI()
{
    DrawDefaultInspector();

    GenNoise script = (GenNoise)target;
    if (GUILayout.Button("Generate"))
    {
        script.RenderNoiseMap();
    }
}

}

Here is a picture of the result:


texts: C++ Namespace vs Reference passed around like crazy - Implement a quest journal

texts:
May sound funny, but that's what the question is about.

Suppose you have this situation:
http://i48.tinypic.com/whl6pk.jpg

Red squares are data types. Hexagons are methods and Journal is the main issue here. Or more exactly, how the link between Game and Journal should be interpreted. Basically, a lot of game components (instantiated inside of Game) will have to gain access to the Journal functionality. The two options that I have thought of myself are the following:

Journal could be a namespace w/ 'globally' used methods and fields. Something like:

journal::AddEntry(someEntry);

OR I could make Journal a Class, just like Game, and instantiate it inside of Game, and then pass a reference to Journal to each property of Game that needs to use the journal. Something like:

  GameProperty *property = new GameProperty(&ourJournal);
  //...inside of property:
  Journal *referenceToJournal;

But then, if I'd delete referenceToJournal, the actual ourJournal object would be deleted too, right?
I'm pretty sure this just complicates things by a lot, and having lots of references towards the same object is a bad habit.

I'm kind of thinking that the:

namespace Journal
{
//Fields and methods go here
}
...
#include "Journal.h"
Journal::method();

is the best way to achieve global visibility for the Journal without much stress. But it kind of hurts, since I come from a C# & XNA background where everything is object oriented. Which is the main reason I have thought of a:

class Game()
{
void loadcontent();
void update();
void draw();
}

logic.

How would you attempt to achieve given the scenario? Instantiate a Journal inside of Game and then constantly pass a reference to Journal to all the other game components (instantiated inside of Game), or just treat everything (including Game) as namespaces to provide 'global' access to all required components?
I'm also thinking about classes with public static fields and methods, but that'd be just like namespaces, at least from my point of view.
Here is some more supportive code, to better describe my view on things (pseudocode for the namespace idea):

//FILE Journal.cpp (implementation of Journal.h)
namespace Journal
{
struct JournalEntry
{
    INT QuestID;
    String Description;
};

Vector<JournalEntry> Entries;

void AddEntry(JournalEntry theEntry)
{
    Entries.Add(Entry);
}

/*
* Used at getting all text that has to be shown on the
*/
Vector<String> GetDescriptionsForEntriesWithQuestID(INT theQuestID)
{
    Vector<String> Descriptions;
    foreach (JournalEntry jEntry in Entries)
    {
        if (jEntry.QuestID == theQuestID)
        {
            Descriptions.Add(jEntry.Description);
        }
    }
    return Descriptions;
}
};

//FILE GameComponent.cpp implementation of GameComponent.h
#include "Journal.h"
void GameComponent::ShowInfo()
{
Vector<String> info = Journal::GetDescriptionsForEntriesWithQuestID(3);
//go through the collection and do stuff
}

Thanks!


texts:
Instead of my usual inheritance heavy game engines I'm toying with a more component based approach. However I have a hard time justifying where to let the components do their thing.

Say I have a simple entity that has a list of components. Of course the entity does not know what these components are. There might be a component present that gives the entity a position on screen, another one might be there to draw the entity on screen.

In order for these components to work they have to updated every frame, the easiest way to do this is to walk over the scene tree and then for each entity update each component. But some components might need a little bit more management. For example a component that makes an entity collidable must be managed by something that can oversee all collidable components. A component that makes an entity drawable needs someone to oversee all other drawable components to figure out the draw order, etc...

So my question is, where do I update the components, what is a clean way of getting them to the managers?

I have thought about using a singleton manager object for each of the components types but that has the usual drawbacks of using a singleton, a way to alleviate this is a bit is by using dependency injection but that sounds like overkill for this problem. I could also walk over the scene tree and then gather the different components into lists using some sort of observer pattern but that seems a bit wasteful to do every frame.


texts: How to have a gradient blur in objects on Unity?

texts:
This is related to a previous question I've asked here:
How to blur entire scene but a specific spot in Unity?

At the time I managed to solve my problem with a "hard" cutoff on the blurred and non-blurred objects. But now I need to have the same effect, but with some sort of "transition" between them, like the objects still being blurred at the edges of the circle "mask" I'm using and getting "non-blurred" as they get closer to the center.

As it is a mobile game, performance is really important, so is there any way of doing that without destroying my fps?

Thanks for your attention.


texts: How to scale game with orthographic camera correctly?

texts: During porting to android I encountered that the game does not fit on the screen in portrait mode. It uses an orthographic camera. How could I scale to game to fit the screen in portrait mode?


texts: 3d transformation of game world keeping gameplay 2d - COCOS2D 2.0

texts:
I want to rotate the game world, may be loading another .tmx file for another dimensions when user want to switch dimension.

The effect what I am looking for is something like the 'side' transition in Fez.

What I have thought of till now:

rotating CCCamera will be mandatory.
Question: How will I have the other part of the level in place while the camera rotates/rotating?
I can load a CCSprite and rotate it accordingly to the 3rd dimension. phew..!!
Question: When the camera and world is rotated, will the player controls work properly.. I think not...?
I think a better option would be to checkout with COCOS3D... there I could implement 3d world... right?
Question: Not sure how well 2d dynamics will work there as I want to user Box2d as physics engine..

Could anyone provide suggestions?


texts: How can I add a new item to my enum list in the inspector?

texts:
I have a list of enums. I want to add a new item to it without scripting to make them more easily modifiable for game designers.
I made an inventory system and I want to define the type of an item. For an example apple is a type of food and stone is a type of object.

Is there a way to group these items in the inspector?

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public const string[] typesStrings = {"Player", "Prop", "Enemy"};
    [System.Serializable]
    public class TypeList
    {
        public enum types
        {
            PLAYER = 0,
            PROP = 1,
            ENEMY = 2
        }

    };

    // MonoBehaviour class
    public TypeList.types selectedType;

    public void Start()
    {
        string selected = TypeList.typesStrings[(int)selectedType];
    }
}

This, however, gives me the following error:

  Assets/grouping.cs(5,31): error CS0134: A constant grouping.typesStrings' of reference typestring[]' can only be initialized with null


texts: How to handle sprite speed when objects move using Box2d?

texts:
I have a basic platformer using Box2d that works great. However, I now want to stop using my default square, and implement some running and jumping animations.

How can I ensure that:

When running, the speed of the running sprite is correct with the current player speed, as to prevent the sprite from 'moonwalking'.
When jumping, play the correct frames at the right moments? I imagine I need to check the vertical velocity and if this is zero again while jumping I'm at the highest point, but how do I track where to initiate the landing animation?


texts: Gesture detection coordinates not synced with viewport

texts:
I am trying to implement pan(float x, float y, float deltaX, float deltaY) from GestureDetector  .
I set the coordinates of the texture to the parameters of the pan , so whenever i drag the texture
on screen it draws there . it worked perfectly .

  Now i put a camera and a viewport in the screen and suddenly the the
  texture isn't following the drag coordinates properly .

here is the create() method where I initialise my camera and viewport

    @Override
public void create () {
    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");
    pos = new Vector2(0,0);

    camera = new OrthographicCamera();
    camera.position.set(width/2,height/2,0);
    viewport = new StretchViewport(width,height,camera);
    viewport.apply();
    gestureDetector = new GestureDetector(this);
    Gdx.input.setInputProcessor(gestureDetector);
}

and here is how i implement the pan method from the interface

@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
    pos.x = x ;
    pos.y = Gdx.graphics.getHeight() - y ;
    return true;
}

The code works fine when i am touching the top left corner of the screen
where the Gesture detector considers the coordinate (0,0) but as I drift towards
the right ,the texture drawn is somewhat ahead of the x coordinate being touched  .
It is working fine with respect to the Y axis .