texts: How to store unique keys for an infinitely generated, chunked world?

texts:
My game is made up of chunks which are identified in world space with and X and Y coordinate. Each chunk contains 16 tiles by 16 tiles by 4 layers. So that I don't have to loop over every single tile every time I want to access things such as hitboxes or animation frames I store that tile's value as keys in various dictionaries such as "Animations" or "Collidables". Until now I have been doing it like this:

        public string GetTileKey(int layer)
    {
        string XString = X.ToString();
        if (XString.Length < 4)
        {
            XString = XString.PadLeft(4, '0');
        }
        string YString = Y.ToString();
        if (YString.Length < 4)
        {
            YString = YString.PadLeft(4, '0');
        }
        return layer.ToString() + XString + YString;

    }

which as you can imagine, slows things down considerably!

After chatting with a few awesome people in discord I was suggested a bitwise method which would store the first few bits as the X coordinate, the second few as the Y, and the last 2 as the layer like so:

public int GetTileKeyAsInt(int layer, IInformationContainer container)
    {
        return (X << 16) | (Y << 9) | layer;
    }

(The container parameter is not currently used, I was trying things out with its X and Y coordinates. It's really just the chunk)

which works fantastic when used with X and Y values which are between 0 and 128 and which are not negative. In addition it guaranteed no duplicate keys.

I quickly realized this wouldn't work with my world, which requires both positive and negative coordinates and an "infinitely" expanding number of chunks.

What is a better way to do this? I was planning on using a float or a double and using the first bit as the sign value, and the next eight (4 and 4) to store the X and Y coordinates of local tiles within chunks and then allocating the rest of the bits to allow for a massive number of allowable chunks. I'll admit I'm not super familiar with bitwise operations or even really the specifics between int, float and double :( but from what I've gathered it doesn't actually make sense to do bitwise operations with anything larger than an Int 32!


texts: Multiplying by delta not giving smooth movement

texts:
I started working on my first proper game but reached a problem straight away. In short I have a game that runs most of the time at 60 fps. ( I am using Libgdx a popular Java framework) but my game object which has a constant velocity and is multiplied by delta, is not moving smoothly. I have tried turning vsync on and off but that does not help. My speed variable is -100, and it is only moving vertically downwards so it is pretty clear if it is moving jerkily or not. Here is my quite simple code:

public class Ball extends AbstractGameObject {

private TextureRegion tex = Assets.instance.ball;
private float speed;

public Drop(Vector2 pos, float speed) {
    super(pos);
    this.speed = speed;

    width = 17;
    height = 32;

    type = Type.Ball;

}

@Override
public void update(float delta) {
    pos.y = pos.y + (speed * delta);
    rect.set(pos.x,pos.y,width,height);

}

@Override
public void render(SpriteBatch sb) {

    sb.draw(tex, pos.x, pos.y, width, height);

}

public float getSpeed() {
    return speed;
}

public void setSpeed(float speed) {
    this.speed = speed;
}

}

It was previously of my understanding that by multiplying by the elapsed seconds since the last frame, it would guarentee smooth movement. Is thing wrong? If so, any suggestions on how to make it smoother?


texts: Predicting trajectory collisions for multiple moving objects

texts:
For the most simple of 2D games, I have implemented a posteriori collision detection (overlapping rectangles) on the xy Cartesian plane, but am now interested in understanding the basics of a priori collision detection...

On Wikipedia's entry on collision detection, I noticed the reference to Newton’s Method.  So, I want to better understand the link between finding zeros of an equation and detecting a posteriori collision.

Let's start with the most obvious case of finding roots of an equation:  If you have a projectile's trajectory modeled as a quadratic function, you can find the roots to predict at what time the height will equal zero (or any other constant height, actually, by just rearranging f(x)=C to be f(x)-C=0 and then finding roots of that expression).

So, as I understand, finding the root can tell me the time at which the object will be at any chosen height.  More broadly, we basically know the (x,y) location of the object for any given time.

But how does root finding, in particular, translate to detecting collisions with another object?  The other object may be stationary, or be moving.  If the latter, do you also determine roots/location of this moving object as well? Calculate the (x,y) trajectory of both objects and determine where they will intersect?


texts: C# (Unity) Use a method common to multiple classes with the same base class

texts:
The Problem:

I'm building one of those empire/kingdom building games and so I am trying to create an efficient way of making a "ResourceManager" class handle the games resources (wood, food, iron, stone). I currently repeat a function 4 times to do the same thing.

Attempt 1:

I created a "Resource" class (abstract) and derived the four resources from it. In each resource there are multiple methods which are similar:

Example Food.CS:

    new public static void AddResources(int amount) {

    Player.currentFoodSupply += amount;
    foodText.text = Player.currentFoodSupply.ToString();
}

Compare to Iron.CS:

new public static void AddResources(int amount)
{
    Player.currentIronSupply += amount;
    ironText.text = Player.currentIronSupply.ToString();
}

The AddResource() function is static because I have other scripts (like buildings, when they get upgraded) needing to communicate with each resource. The base building class currently has a method like this:

public void DeductResources()
{
    Food.DeductResources(FoodCost);
    Wood.DeductResources(WoodCost);
    Iron.DeductResources(IronCost);
    Stone.DeductResources(StoneCost);
}

This seems like it's so repetitive that there needs to be a more efficient way to do this.

Attempt 2:

A "ResourceManager" class that anything to do with the 4 resources can go through this one script. I can update that one script instead of numerous scripts that does something with the resources.

Where I am undecided is this one:

public static void DeductResources(Resource resource, int amount)
{
    if(resource.GetType() == typeof(Food))
    {
        Player.currentFoodSupply -= amount;
        resource.resourceText.text = Player.currentFoodSupply.ToString();
    }
    else if (resource.GetType() == typeof(Wood))
    {
        Player.currentWoodSupply -= amount;
        resource.resourceText.text = Player.currentWoodSupply.ToString();
    }
    else if (resource.GetType() == typeof(Iron))
    {
        Player.currentIronSupply -= amount;
        resource.resourceText.text = Player.currentIronSupply.ToString();
    }
    else if (resource.GetType() == typeof(Stone))
    {
        Player.currentStoneSupply -= amount;
        resource.resourceText.text = Player.currentStoneSupply.ToString();
    }
}

It looks like it works and I can't see a way around calling the above method 4 times as I need to know how much food or wood to add or deduct.

Does anyone have any suggestions please on how to improve this code/call the method once?

I'm always willing to learn! Thank you


texts: How to make high quality gifs of Unity game play

texts:
I've seen several Unity game play gifs, mostly on twitter. Are there any tools for making high quality gifs in Unity that are quite flexible? For example, I video recording tool that captures the game window and allows users to make gifs of portions, possible specifying the desired quality. Generally, I am looking for a tool that is quite flexible (has a lot of options for capturing gifs) and possibly game window video.

UPDATE

Some examples are here and here. Generally, several of the gifs that are hash-tagged madewithunity a really high quality.


texts: Moving a character to a point without any floating point operations

texts:
So I'm writing an adventure game for MSDOS, just a fun challenge for me. I'm trying to get the character to walk along a straight line to his destination (either the next navMesh node or where you clicked). Normally I would simply store the characters x,y as floats and add the direction vector to it for each move, the problem is that cpus before the 486 didn't have FPUs at all so floats are out of the question. So naturally I thought about Bressenham's line algorithm which can be done using all ints. Taking inspiration I came up with this function here which runs every frame:

void character::doWalk()
{
    int x_diff = destination.x - x;
    int y_diff = destination.y - y;

    int x_dist = abs(x_diff);
    int y_dist = abs(y_diff);

    int walk_x_dir = x_diff > 0 ? 1 : (x_diff < 0 ? -1 : 0);
    int walk_y_dir = y_diff > 0 ? 1 : (y_diff < 0 ? -1 : 0);

    if(y_dist >= x_dist || yerror > 0)
    {
        y += walk_y_dir;

        yerror -= path_dist_x;
    }
    else
    {
        yerror += path_dist_y;
    }

    if(x_dist >= y_dist || xerror > 0)
    {
        x += walk_x_dir;

        xerror -= path_dist_y;
    }
    else
    {
        xerror += path_dist_x;
    }
}

path_dist_y is the vertical distance calculated when the character begins walking path_dist_x is the horizontal distance.

This algorithm almost works, it seems that he begins walking at an angle just too shallow to get to the point correctly and he has to change direction near the end of his walk to make it to the point. Any idea what else I could try?


texts: Creating natural environments that can run on lower end computers in Unity3D/C#

texts:
So, I'm starting work on a project soon that will require me to create realistic environments that can preferably run on PC's besides high quality ones. The goal is to get as real an environment as possible while still being easy(ish) to run.

The only problem is I've NEVER done anything with 3D environments, making trees sway, grass move, lighting, etc. Can anyone give me any help? Perhaps describe how it's done? Link me to articles? I'm just looking to be pointed in the right direction, not for you to write the code for me.

Any help at all would be greatly appreciated, I'm using Unity3D and C# as my language.

Thanks,

Tim.


texts: Why doesn't my game start in landscape mode?

texts:
I want my game to run on all Android devices in LANDSCAPE_FIXED mode, but this mode works only for some screen resolutions. PORTRAIT_FIXED works well for all devices. I'm testing this on and emulator.

How can I achieve this? Here's my camera/engine initialization code:

public EngineOptions onCreateEngineOptions() {
    cw=480;
    ch=320;
    camera = new Camera(0, 0, cw, ch);
    EngineOptions engineOptions = new EngineOptions(
        true,
        ScreenOrientation.LANDSCAPE_FIXED,
        new RatioResolutionPolicy(cw, ch),
        this.camera
    );
    engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
    return engineOptions;
}


texts: Mouse position not updating while mouse buttons are pressed

texts:
I have a simple mouse manager class: https://imgur.com/MuUhh73

Whenever any of the mouse buttons are pressed the mouse position does not update when calling getMouseX() or getMouseY() on the mouse manager object via a basic handler that gets passed everywhere.

Is the problem in my implementation or is it a bug in general?


texts: Orthographic Camera Movement inside Rotated Boundary Rectangle Weird Behaviour [Unity3d]

texts:
Basically I have an orthographic camera that is looking at a simple square. The camera is sitting above the square and tilted by x: 45° and y: 45°, so the camera sees the square as a rhombus / diamond shape.
I want the camera to be moveable within a rectangular boundary that appears to be leveled with the camera, so it would need to be rotated by 45° around the y-axis (up-vector in Unity) in World-coordinates. I already figured out the math to constrain the camera to this shape, but there is a weird thing going on when the movement gets clipped: The camera doesn't follow the outline perfectly, but in a rounded shape (see screenshot). Could this be due to a rounding error? Code snipped below.

using System;
using UnityEngine;
using static UnityEngine.Mathf;

public class InputController : MonoBehaviour
{
    private const float CamHeight = 10f;
    [SerializeField] private GameObject gameBoard;
    [SerializeField] private GameObject camBounds;
    [SerializeField] private float camBoundRadius = 5f;
    private Vector3 _camOrigin;
    private MeshCollider _collider;
    private Vector3 _difference; // Change in position of mouse relative to origin
    private Camera _mainCamera;
    private Vector3 _origin; // Place where mouse is first pressed
    private Plane _worldPlane;

    private void Start()
    {
        _mainCamera = Camera.main;
        if (_mainCamera is null) throw new Exception("No main camera could be found!");
        // Set the camera so that the board is always in the center
        _camOrigin = new Vector3(
            -CamHeight / Sqrt(2f),
            CamHeight,
            -CamHeight / Sqrt(2f));
        _mainCamera.transform.position = _camOrigin;
        _collider = gameBoard.GetComponent<MeshCollider>();
        _worldPlane = new Plane(Vector3.up, 0); // For dragging the camera around
    }

    private void LateUpdate()
    {
        if (Input.GetMouseButtonDown(0)) _origin = MouseWorldPosition();
        if (Input.GetMouseButton(0))
        {
            _difference = MouseWorldPosition() - transform.position;
            var newPos = _origin - _difference;
            var absDiff = newPos - _camOrigin;

            var angle = Angle2Pi(Vector3.right, absDiff);
            var constraint = SawTooth(angle);

            if (absDiff.magnitude < constraint)
                transform.position = newPos;
            else
                transform.position = _camOrigin + absDiff.normalized * constraint;
        }
    }

    private Vector3 MouseWorldPosition()
    {
        var clickedPoint = Input.mousePosition;
        var ray = _mainCamera.ScreenPointToRay(clickedPoint);
        var worldPos = Vector3.zero;

        if (_worldPlane.Raycast(ray, out var raycastHit)) worldPos = ray.GetPoint(raycastHit);

        return worldPos;
    }

    private float SawTooth(float theta)
    {
        var x = 4f / PI * camBoundRadius * (1f - 1f / Sqrt(2f));
        x *= Abs(theta % (PI / 2f) - PI / 4f);
        x += camBoundRadius / Sqrt(2f);
        return x;
    }

    private static float Angle2Pi(Vector3 from, Vector3 to, Vector3 normal = default)
    {
        if (normal == default) normal = Vector3.up;

        var angle = Vector3.Angle(from, to) * (PI / 180f);
        var sign = Sign(Vector3.Dot(normal, Vector3.Cross(from, to)));
        angle = 2f * PI - angle * sign;

        return angle;
    }
}


texts: The reasons behind Unity3D engine design (game object/transform component)

texts: I'm trying to understand the reasoning behind Unity3D engine design and this is something I can't get my head around yet: why is transform data stored in a separate component, instead of being a part of GameObject, like name, layer masks and tags? It cannot be removed like all of the other components anyway, there are no alternatives and thus no need for it to be removed.


texts:
I know what it's used for, I know what it does.

What I am essentially asking is what is the math/code behind how it works?

I'm aware that any custom implementation would likely be slower than an engines official implementation, I just am interested in how it works.


texts:
I've been working on a 6DOF camera that I want to be able to "align" to any walls orientation to make it feel like I'm standing on that wall.

I'm thinking it's a simple matter of finding the right amount needed between the current cameras rotation and the ground orientation and apply the difference in roll, but I'm terrible at vector math. Any help?

I use C# XNA Quaternion/Matrix/Vector3, but any pesudo math can do as thats what I'm struggling with.

Edit: I would also like this to work on spheres & cylinders, so I'd also need a way calculate the difference in pitch from changing from one vector to avoid making the camera feel like it looking upward if walking a step forward on top of a sphere for example.


texts: Path tables or real time searching for AI?

texts:
What is the more common practice in commercial games; path lookup tables or real time searches?

I've read that in many games path lookup tables are pre-calculated and baked into each map, so to speak, then steering behaviour is used to handle dynamic obstacles.

or is it better practice to use optimised hierarchical A* searches? I understand the pro's and cons of each, I'm just curious as to what is most often used in the industry.


texts: SDL2 not rendering larger texture to smaller texture

texts:
With SDL2 I created texture1 of 28800 x 28800 which contains a drawing of a grass background all over the texture.

Then I created texture2 of 2880 x 1620.

Then I set the render target to texture2.

The I set the logical size to 2880 x 1620.

The I renderclear texture2.

Then I rendercopy a rectangle of 2880 x 1620 from texture1 to texture2

Then I renderpresent texture2 but my screen is black.

Is that because I am trying to copy from a larger texture to a smaller texture? What are the limits when it comes to copying from texture to texture with SDL2?

Let me know if you need my code and where to put it. Some websites don't like it when you put your code in a post.


texts: Trying to render a geometry with OpenGL, but can't seem to

texts:
I have a Renderer component which can render a Scene. Assume the scene is just a container for Renderable objects. A Renderable is composed by a Geometry and a Material. I call that a Mesh. When rendering the multiple renderables, that's essentially what I do, for each renderable:

var (
    vbo      uint32
    ibo      *opengl.IndexBuffer
    geometry = renderable.GetGeometry()
)

gl.BindVertexArray(r.vao)

gl.GenBuffers(1, &vbo)
gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
gl.BufferData(gl.ARRAY_BUFFER, int(unsafe.Sizeof(geometry.GetVertices())*VertexSize), nil, gl.DYNAMIC_DRAW)

ibo = opengl.NewIndexBuffer(geometry.GetIndices(), uint32(len(geometry.GetIndices())))
ibo.Bind()

gl.DrawElements(gl.TRIANGLES, int32(ibo.Count), gl.UNSIGNED_INT, gl.Ptr(geometry.GetIndices()))

ibo.Unbind()
gl.BindBuffer(gl.ARRAY_BUFFER, 0)
gl.BindVertexArray(0)

opengl.IndexBuffer is my implementation of an index buffer. It simply does:

gl.GenBuffers(1, &indexBuffer.ID)
gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer.ID)
gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, int(count)*4, gl.Ptr(&data[0]), gl.STATIC_DRAW)

However, I can't seem to draw my geometry. What am I doing wrong?


texts: Finding possible moves for an entity in a 2d tiled game

texts:
I'm having issues coming up with a specific search term for this, but how would one go about finding the possible moves in a 2D turn-based strategy game (i.e. FF:Tactics, Fire Emblem, Advance Wars).

I'm not so much thinking about terrain (or even collision) at this point. I'm just wondering what algorithm I can use to figure out that X entity can move 5 tiles and attack 2 farther tiles than that.

I know I can use something like Dijkstra to find the distance between two points. One possible implementation is starting at the players location and then branching off from there until the distance returned by Dijkstra is greater than the move count.

Just wondering if someone could point me in the right direction (i.e. name of algorithms, technique, articles, etc).


texts: How do you create your levels containing curved slopes in Box2d?

texts:
I have just started developing games for iPhone in Cocos2d and am currently working on a Box2D prototype. I know this is not an easy start, but I have experience in the AS3 port of the physics engine. And ... I am stubborn.

My question is:
How do you implement and create your levels in the project. Is there a good parser out there or maybe a nice approach you guys know of? I am looking for a way to create curved slopes and of course circles and rectangles.

I have read about LevelSVG but it seems to add a lot of functionality that I don't want. I am a Flash game developer and I am used to writing the game logic by myself. Is this product worth the money if all you need is the parser?

Thanks


texts: Unity Collision Difficulties (How do I make a ground in unity with lots of pieces that doesn't have poor collision?)

texts:
So I'm working on this game that I came up with the idea for while watching the Unity Roll-a-ball tutorials. So it's probably important to note that I'm extremely new to game design and I don't have a whole lot of experience in programming.

So the game idea that I had is a lot more complex than what it should be for someone who's pretty much completely new to game design, so I guess I'm trying to break it down into smaller bits until I have enough experience to build it into a cohesive game.

Currently what I want to work on is a game where you play as a sphere rolling down a plane with open edges so you can fall off. There are walls that you have to avoid, and if you run into them it will take away from the space between the walls and the edge of the plane. I guess I was sort of thinking of having a sort of similar visual style as bastion in that sense.

The way I thought I would go about this is to break the plane up into smaller squares and then do some programming so that when you run into the walls the smaller squares at the edge of the plane fall off. Though before I could even get to programming I ran into a big problem. Because of the way Unity physics work and the way I built the ground, the player collision with the ground is god awful. When I was just testing it with some basic controls the ball would roll all choppy and if I picked up enough speed it would start to jump. I assume this is because it's colliding with all the edges of the grid system that I built.

Does anyone know of any way I can program the edges to not interact with the player? Or if there's a better way to go about doing this?


texts: Client-Server Game Communication (w/ Protobuf, Relevancy and Delta Compression)

texts:
So, I have reached another problem while trying to implement my client-server communication. From everything I've read there are three main ways to minimize packet size:

Only send what has changed to the client (Delta Compression)
Only send what gameobjects are relevant to the client (Relevancy)
With large packets, zip/compress them (L4Z?) [Not key for this question]

I have already implemented a delta compression scheme throughout my codebase using dirty bits and some interfaces. It's not as easy to use as I'd like, but it is decent and it works. Now I need to figure out how to add relevancy. I can certainly determine relevancy for each GameObject, but keeping track of all these deltas and which client has received them I think could get inefficient and complicated.

I considered having Players keep a NetworkComponent that tried to keep track of sending and maintaining what hasn't been sent, but I feel that could get complicated.

Advice on how to implement or improve either of these?


texts:
Using libGDX I have created a few 2D screens, such as a splash screen and a main menu, and also created a 3D scene which I want to be able to load when clicking a button on the main menu.
I know how to add a listener but I don't know what command to use to show the 3D scene on the screen. If I use setScreen(new World3D) (or other similar extended methods) it gives me:
 World3D cannot be cast to com.badlogic.gdx.Screen

What I want to know is how to get from the 2D screen to the 3D scene. Do I wrap the 3D scene inside the screen or am I doing it right but my World3D class is not set up properly?
Here is a pastebin of my World3D class in case that is the problem.

NOTE: The classes are in separate sub-packages but the proper imports have been added in the required classes.


texts:
I am working on my collision system right now and I wondered how you can actually walk on a mesh. For example I'm thinking about a dynamically created little village and I want to be able to move the player across roofs etc.

I read about two different approaches to that problem.

Simulate the next step and test if the step can be performed. If it's all right, perform that step or abort otherwise
Perform the step and let the collision system handle a collision in the next frame.

Now, with regards to speed and accuracy, which one is better suited for my problem. As a sidenote: the player should also be able to climb stairs and I also want to prevent the player from moving on very steep parts of the model.


texts:
I am working on a physics driven pressable button, but I cannot seem to tackle the minimum and maximum limits.

This is the rig I have set up for the button (as it looks when pressed down).
2D view:

3D view:

The idea is that the box collider is a trigger and the button (cylinder, mesh collider) is a rigidbody with configurable joint, locked and limited on a single axis. I am using configurable joint, as that's the only one that supports basic, linear restrictions.

I have set up the configurable joint to restrict motion on a single axis, but the joint only allows single dimensional limit, that is applied to both directions. Screen capture of relevant configuration:

Basically, the opened Linear Limit section is the last property that has been changed for the joint - anything else are defaults and irrelevant (at least I haven't found my solution in the properties below, mostly angular stuff).

The limit of 0.2 units work, and the button can be pressed - it only gets pressed until those 0.2 units and thats the expected behaviour.
The unexpected is that sometimes the angle at which I hit the button, adds force to the button outwards from the box, and it moves 0.2 away from it, ending up like this:

Obviously, the specified limit of 0.2 units constrain the movement in both directions from the anchor, actually resulting in the range of -0.2 to 0.2 (relative to anchor).

How, and is it even possible, to restrict the movement only in a single direction relative to anchor?


texts:
I try this code from tutorial for learn Modern OpenGL in Visual Studio 2015:
http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/

With GLUT (from other tutorial), it workink fine (other project with glew32.lib and freeglut.lib).
With GLEW Project after add glew32.lib and glfw3.lib, lesson 2 has problem in: glDrawArrays(GL_TRIANGLES, 0, 3);

It return linking error in compiling:
LNK2019 unresolved external symbol __imp_ glDrawArrays@12 referenced in function _main

This code:

// Include standard headers
#include <stdio.h>
#include <stdlib.h>

// Include GLEW. Always include it before gl.h and glfw.h, since it's a bit magic.
#include <GL/glew.h>

// Include GLFW
#include <GL/glfw3.h>

// Include GLM
#include <glm/glm.hpp>
using namespace glm;

int main()
{
    // Initialise GLFW
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

    // Open a window and create its OpenGL context
    GLFWwindow* window; // (In the accompanying source code, this variable is global)

    window = glfwCreateWindow(1024, 768, "Tutorial 01", NULL, NULL);

    if (window == NULL) {
        fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window); // Initialize GLEW
    glewExperimental = true; // Needed in core profile

    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        return -1;
    }

    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    static const GLfloat g_vertex_buffer_data[] = {
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f,  1.0f, 0.0f,
    };

    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    do {
        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
            0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
            );

        // Draw the triangle !
        glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle

        glDisableVertexAttribArray(0);

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

        // Check if the ESC key was pressed or the window was closed
    } while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);
    return 0;
}


texts: Rotating towards a target in top-down 2D game

texts:
I use the following code to rotate a transform towards another. And it's working fine. However, I want to lerp it over time period.
public void RotateToward(Transform target)
{
  Vector3 from = transform.up;
  Vector3 to = target.position - transform.position;

  float angle = Vector3.SignedAngle(from, to, transform.forward);
  transform.Rotate(0.0f, 0.0f, angle);
}

An example would greatly help.


texts: Detect click on Triangle and Circle buttons

texts:
How can I detect clicks on a texture (which will be a button in my game) which has the form of a triangle or circle. I only know the rectangle solution which uses the position, width, and height; which won't work because clicks will be detected on transparent pixels.

I have heard of pixel-perfect collision, would that be the right way to do this?

It would be great if someone could give me a example for such a solution.


texts:
I have 3 related questions:

What are the main optimizations related to power of 2 dimensions for 1D/2D/3D textures? This question gives some answers like mipmapping, but are not well explained and the list of optimizations does not seem to be complete. I want a complete ordered list from most important to less of the optimizations with complete explanations, with references replacing full explanations only where full explanation would overwhelming, and proper references (paper/graphics official page [OpenGL/Vulkan/CUDA]) for every statement about explained optimization. When the comparation is not direct, take a guess based on the one that would improve overall performance most in majority of computer graphics applications. Furthermore I want to specify which of this optimizations are available at least for OpenGL and CUDA. More specifications would be acclaimed.
What benefits exists for divisible by 8 dimensions? This article states the rule as an alternative/complement to the power of 2 one but does not give explanations nor references.
Is there any benefit for divisibility by a larger number? This article uses divisible by 32 dimensions. I know that CUDA has a warp size of 32 and that blocks should be multiple of 32 to have a good overall average utilization, but I do not know if this could be related to texture sizes and would like to know if the answer is no.

In many places posibilities for texture optimization are loosely stated and not properly documentated. This question aims at solving this issue.


texts: 3D BSP rendering for maps made in 2d platform style

texts:
I wish to render a 3D map which is always seen from top, camera is in sky and always looking at earth. Sample of a floor layout:

I don't think I need complex structures like BSP trees to render them. I mean I can divide the map in grids and render them like done in 2D platform games. I just want to know if this is a good idea and what may go wrong if I don't choose a BSP tree rendering here. Please also mention is any better known rendering techniques are available for such situations.


texts: Centralized User database for multiple Systems

texts:
I was wondering, how do large companies handle user accounts and allow different applications to access them.

One example that comes to mind is Riot, their game League of Legends has a global user account that allows you to login to forums and the game client itself.

What sort of method would they be using to allow multiple systems to access this database.


texts: How to sub-divide a hexagonal grid reference system

texts: I have been using @amitp's excellent guide (and javascript library) to create a hexagonal grid system https://www.redblobgames.com/grids/hexagons/. I'm using flat-top, inverse-y cubic/axial system. However, I have elements that are located on the vertices, rather than "within" a tile. How would I refer to their position? I have considered using the index of the corner, but then the question is which  tile do I use as my base? I would also like to extend the concept so that I could precisely position an element anywhere within a tile. I am thinking of something relating to the Ordnance Survey's method of sub-division within the British National Grid (OSGB 1936) but I cannot get my head around how this relates to a cubic/axial coordinate system.


texts: (Unity) how to write my own raycasting functions

texts:
I am making a game in curved space in Unity and I am trying to figure out the best way to handle raycasting. For my purposes the Ray struct doesn't carry enough information so I started by writing a custom ray struct. I suppose next I need to write a custom collider class but I'm not sure whether I should inherit from Unity's Collider class. The Collider class has a Raycast function that I could overload, but the function signature takes normal Rays. It would be cool if I could just interface with the normal Unity physics raycasting system, but it looks like that won't work because it's all built around passing around Rays.
So what I'm thinking is I'll write a custom static physics class which will have a raycast function which will loop over all the custom colliders in the scene and find which one my custom ray hits first. I suppose I will also have to write my own version of the RaycastHit class since the existing RaycastHit has a field that carries Colliders.
The alternative is my custom collider could inherit from the Unity Collider and add a new version of Raycast that takes my custom rays. Then I could use the existing RaycastHit class, but I would still have to write my own physics class.
So my first question is how I should structure all this. I've given it some thought but I'm looking for input from someone with a deeper understanding of Unity. Next, I have one particular object that I'm interested in raycasting that will have a large mesh and I need to know which triangle is hit by the raycast. I suppose I should make a custom mesh collider class that inherits from MeshCollider.
So I'm just looking for insight into the cleanest way to organize all this. Thank you for any advice you can offer!


texts: Welzl Algorithm to find the Smallest Bounding Sphere

texts:
I'm implementing Welzl's Algorithm to find the Smallest Bounding Sphere.

In brief, the algorithm works by maintaining:

a set of points to contain in the sphere (inside its interior, or on its boundary)
a set of points known to be on the boundary of the sphere (the "set of support")

It works recursively, starting with the full set of points in the contained set and no boundary points in the set of support. At each level, it tries removing a point from the contained set, and recursively finding the minimal bounding sphere of this reduced set (with the current set of support).

If the removed point is in/on the resulting sphere, then it returns that result up the recursive chain.
If not, then the removed point must be on the boundary of the minimal bounding sphere, so it adds it to the set of support and recurses again.

Once it boils down to no remaining contained points or 4 boundary points, the recursion bottoms-out and returns an explicitly calculated sphere based on the boundary points found.

I'm not sure of a few details of the implementation, and haven't found on the net the answer to my questions :

How can I construct a sphere is uniquely defined by four (non co-planar) points?
Do I have to check in the algorithm if these four points are non co-planar?
I used the barycenter (centroid) of the boundary points in by set of support when the number such points is three or more. Is that correct ?
My algorithm may fall into cases with more than four boundary points in the set of support, so I had to add a default case to handle this - is this normal?

Here's my current code:

Sphere ComputeMinimalBoundingShpere(glm::vec3*              points,
                                    std::size_t             numberPoints,
                                    std::vector<glm::vec3>& sos,
                                    std::size_t             numberSos)
{
  // Stop the recursion when we have no more points
  // Or the number of support is more than three
  if (numberPoints == 0 || numberSos >= 4) {
    switch (numberSos) {
      case 0: return Sphere();
      case 1: return Sphere(sos[0], 0.000f);
      case 2: {
        const glm::vec3 center = (sos[1] - sos[0]) * 0.5f;
        return Sphere(center, glm::length(center) * 0.5f);
      };
      case 3: {
      // If we have three points: Look for the barycenter
        const glm::vec3& A = sos[0];
        const glm::vec3& B = sos[1];
        const glm::vec3& C = sos[2];
        const float      v = 1.0f / 3.0f;
        const float      w = 1.0f / 3.0f;

        const glm::vec3 P      = ((1 - v - w) * A) + v * B + w * C;
        const float     radius = glm::length(P - A);
        return Sphere(P, radius);
      };
      case 4: {
      // If we have four points: Look for the barycenter
        const glm::vec3& A = sos[0];
        const glm::vec3& B = sos[1];
        const glm::vec3& C = sos[2];
        const glm::vec3& D = sos[3];
        const float      v = 0.25f;
        const float      w = 0.25f;
        const float      x = 0.25f;

        const glm::vec3 P = ((1 - v - w - x) * A) + v * B + w * C + x * D;
        const float     radius = glm::length(P - A);
        return Sphere(P, radius);
      };
      default:
        assert(false && "We cannot have more than four Set of Support");
    }
  }

  const int    indexPoint = numberPoints - 1;
  const Sphere smallestSphere =
    ComputeMinimalBoundingShpere(points, numberPoints - 1, sos, numberSos);
  if (smallestSphere.contains(points[indexPoint])) { return smallestSphere; }

  sos[numberSos] = points[indexPoint];
  return ComputeMinimalBoundingShpere(points, numberPoints - 1, sos,
                                      numberSos + 1);
}


texts:
In Construct 2 example about creating an animated player, they used more than 8 events:

4 events to store movement direction into Direction variable from Player.8Direction.MovingAngle

4 events to select animation based on Direction value

1 event to stop animation

Apparently if would be much easier to do the same with simple if-else code with 4 or 5 cases. Is it possible in Construct 2?

UPDATE

I didn't find scripting, but was able to express the same example in more condensed way:

All names are from example.


texts: How can I pass an enum value to the OnClick method of a button?

texts:
I am making a UI system for my game where I want to use an enum to define different UI modes. But OnClick function on button doesn't show method which receive enums.

I heard I can pass an integer value to OnClick method and then somehow transform it into an enum. What can I do about it?


texts:
Assuming you already have the best-choice algorithm, what low-level solutions can you offer for squeezing the last few drops of sweet sweet frame rate out of C++ code?

It goes without saying that these tips only apply to that critical code section that you've already highlighted in your profiler, but they should be low-level non-structural improvements.  I've seeded an example.


texts:
What dimensions should you use for a perspective projection frustum? Initially I created a perspective matrix based on the width and height of the screen, with a calculated zNear value based on a 45degree FOV.

// OpenGL example
// For height of 800, zNear is calculated to be ~965.
zNear = (height / 2.0f) / tan(Deg2Rad(45.0f) / 2.0));
zFar = 100000.0f;
glFrustum(-width / 2.0f, width / 2.0f, -height / 2.0f, height / 2.0f, zNear, zFar);

But then I realised that this isn't a sensible idea and you shouldn't base your frustum on pixels, and you should use logical units instead (else when the window / screen changes size, objects will change position or size).

So now I'm wondering what dimensions I should use for the logical planes of the frustum? How do you choose a zNear value? Is it sensible to base it on the desired FOV? I'm aware that having a small zNear value can mess with the z-buffer, which is why I initially based it on the FOV.

My current thoughts are of using a logical near plane of TopLeft: -10000, -10000 and BottomRight: 10000, 10000. But then that generates a zNear value of ~24142 based on 45degrees FOV, which seems awfully high. What advice do you have? What dimensions should you use for a projection frustum?


texts:
I'm just a little confused with all of the news recently regarding the cancellation of mobile flash, so was hoping for a little help. I've had a search through and can't find the answers to these questions, so any help would be great.

First up, I'm looking to create a game in Flash first, to test whether the concept works as a fun game (on Newgrounds/Kongregate/Facebook etc.). Would it be best to use Flash CS5.5, or Flash Builder?

Secondly, with mobile flash now being discontinued by Adobe, could I still port this game over to iOS through the Flash platform, or would it be better at that point to re-write the whole game using Objective C? (NOTE: I'm not an Objective C developer, but am instead a Javascript and Actionscript dev).

Any help would be great. Thanks!


texts: Why are triangle fans not supported in Direct3D 10 or later?

texts:
As covered in the documentation, triangle fans not supported in Direct3D 10 or later.

Why?  Are there inherent drawbacks to working with triangle fans?


texts: Environment mapping - cube mapping using OpenGL

texts:
I'm trying to do cube mapping.
Problem is that I'm getting this:

This is what I get when I rotate it:

But it should look like this

Here is code for vertex shader

varying vec2 tex_coord;

void main()
{
 vec3 v = vec3(gl_ModelViewMatrix * gl_Vertex);

 gl_TexCoord[0].stp = normalize(gl_Vertex.xyz);
 gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

 //gl_ModelViewMatrix * gl_Vertex
}

fragment shader

uniform samplerCube _tex;
void main()
{
 //gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
 gl_FragColor = textureCube(_tex, gl_TexCoord[0].stp);
}

Could you please tell me what am I doing wrong?


texts:
So, yeah. Mobs (including, and indeed especially, the player), physics engine running (cannon.js), first-person perspective, fairly low-poly-count world because I'm targeting WebGL. I'm trying to represent my mobs within the physics engine, moving them by applying forces or impulses, and I'm having some problems:

1) Ramps! The FPS Way seems to be that critters run uphill and downhill and on the flat, all at the same speed. But of course even-slightly-realistic physics really wants you to go slower uphill, especially if you add friction to prevent "standing" mobs from sliding downhill. I've tried compensating for this by calculating how fast the mob "wants" to go, and applying force proportionate to the difference between its actual velocity and desired velocity, but it just Ain't Right. Also, the mobs have a tendency to jump up off the top of staircases.

2) Falling over! To make the mobs collide with things, they have to be represented by some appropriate shape. I've tried a few different ones. Particles are an obvious lose, and fall into every possible crack in the geometry. A box the approximate shape of the bounding box for a standing person falls over constantly, especially on slopes. Putting the center of mass for the object at the bottom of the box helps, but only somewhat. Using a lower, flatter shape-- think "coin with beveled edges"-- prevents the falling down, but fails at detecting collisions. The last thing I tried was a sort of egg shape, which stays up but staggers like a drunken sailor.

Obviously, I'm missing something. What? Do people just have to have Special Physics Of Their Own? Should I toss the whole thing and write that car game instead?


texts:
This is the problem I have. I have created a shader that draws circle. But depending on the distance from the camera thickness changes.

Is it possible to keep thickness constant?


texts: Using IPAD's as controllers for a Unity game

texts: We are making a Multiplayer game using Unity. The actual game would be run from a PC projected on a screen and the players would be using their respective Ipad as a controller to play the game. I am not sure how difficult this would be to achieve inside Unity but I am assuming that all the game data inside Unity would need to be fed and retrieved from some kind of a server. How would this be possible with Unity because each Ipad would have a separate Unity build and also a separate build for the PC from where the actual game would be running.


texts: Why does simply trying to add sound break literally everything

texts:
So I have a script for an object that when shot explodes and it worked literally perfectly until I tried to add sound at which point it not only didn't play the sound but also stopped exploding, which was pretty rude of it.

Here's my code since I have no idea what's wrong:
(Unity C#)

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

public class ShootyTarget : MonoBehaviour
{
    public float health;

    public GameObject destructionPrefab;

    public GameObject explosion;
    public GameObject shockwave;
    public GameObject debris;

    public AudioSource splodeSound;

    void Start()
    {
        splodeSound = gameObject.GetComponent<AudioSource>();
    }

    void FuckingDie()
    {
        splodeSound.Play();

        Instantiate(explosion, transform.position, transform.rotation);
        Destroy(gameObject);
        Instantiate(shockwave, transform.position, Quaternion.Euler(new Vector3(90, 0, 0)));
        Instantiate(destructionPrefab, transform.position, transform.rotation);
        Instantiate(debris, transform.position, transform.rotation);
    }

    public void takedamage(float amount)
    {
        health -= amount;
        if (health <= 0f)
        {
            FuckingDie();
        }
    }
}
```


texts: Gamma-Correct rendering without floating-point rendertargets

texts:
When using a gamma-correct pipeline, you have to work with floating-point rendertargets. Otherwise, you will get severe banding due to the insufficient precision of the usual 8-bit-per-channel integer rendertargets.

Is there any way around this? Any good way to implement gamma-correct rendering without using floating-point rendertargets?

This is on desktop PCs using Windows and DirectX.


texts:
So like most games, I have inventory screens, equip screens, shop screens, and all that. I've previously been making each "screen" controlled by its own script (which is normal I think), and I draw the screens using GUI. However, I'm worried about having multiple OnGUI functions in my game (one OnGUI for each "thing" I draw [eg Inventory or Shop]) since OnGUI really isn't that best for performance. How should I solve this problem?

I thought about making each screen its own scene in the game but I wasn't sure if that would help things much.


texts: How to draw Tiled map with MonoGame.Extended v0.6.266 beta?

texts: I just recently installed MonoGame.Extended v0.6.266 beta because I needed some functionality that wasn't in v0.5 official. However, I noticed that the draw() method for TiledMap.cs has been removed. This is also the case for TiledLayer.cs. So my question is how do I draw the map and its layers? And I know that this is not an issue with the the way I installed the beta, because I scanned through the source files on the GitHub repo and saw that draw() was indeed removed.


texts: How do I make a sprite appear to sway with the wind?

texts:
I'm trying to find a method to simulate the effects of wind on various sprites in a side-view 2D scene. What relatively simple technique could I use for this?

What I have in mind is to give these sprites a "spring" effect that I could hand a force that rotates them in a specific direction and eventually degrade the force and bring the sprite back to its "resting" rotation over time with a little bit of rebound/wobble/sway... I don't understand how I can mathematically create the elastic/spring effect using rotation, taking into account things like mass, resistance, or stiffness. How would I go about doing this in code?  It doesn't have to be super realistic.

I'm hoping to set up a global wind variable that gets applied to sprites starting on one side of the screen and making its way to the other to look like a gust of wind passed through. I should be able to accomplish this once I have a method for applying a wind force to a single sprite.

How can I do this?


texts: One Android app, dynamic load several Unity games

texts:
I'm a newbie in this unity world, exciting about everything in it.

Days ago I came up with this idea:

One day someone finds this android app, naming "Blahblah Game Engine" or anything else. This app has to be very small, containing only some simple activity and Unity runtime, without further resources related to any specific game.
He installs it and sees an android activity, maybe a webview, showing a list of unity games the server currently hosting, produced by the very same Blahblah company.
Then he clicks on one and this "Blahblah Game Engine" loads the game build via network, starts an Unity activity, without prompting an installing dialog.
He can exit the current game whenever he likes, returns to the previous game list, and plays another, all working well in one app's lifetime.

In a word, the user experience is very much like how we play games on www.kongregate.com with pc browsers: light-weight app, mutiple games in one list, all loads via network, playing right away and installing-less.

Any game that listed in this app should not be installed as a standalone android app, it should be part of the "Blahblah Game Engine", stored as a file inside data folder of "Blahblah Game Engine", run as an activity of "Blahblah Game Engine".

Is it possible with Unity 5, both technically and legally? If I were to start this "Blahblah Game Engine" project, should I choose Unity 5 personal or pro licence?


texts: Suboptimal A* Pathfinding Solution Example using Manhattan Distance Heuristic

texts: I believe using an overestimating heuristic with A* is not guaranteed to find the shortest path. Assuming an agent can travel as a bird using euclidean distances, the manhattan distance provides just such an overestimate; and hence is inadmissable. Can an example graph be provided wherein the use of A*, with a manhattan distance heuristic, can be shown to give a different result than it would by using the euclidean distance?


texts: How to Bring the Scene View Camera Controls into Game View

texts:
I've got a scene with a big sphere in the centre (the Earth) and a lot of smaller spheres around (the stars).

Above is a screengrab in Scene View with the camera in the Front View position.

I really like the controls in Unity's Scene View when moving around the viewport and I was wondering whether it can be brought into the Game View.

How can I do this?


texts:
I have script that makes waves of enemies. It selects enemy from array randomly. I want to add function allow me to select any object in my array and instantiating it for number of times. In wave 1, randomly select enemy from enemy list and represent for several of time. In wave 2, I want to select from my enemy list, and how many will instantiate, and time between spawn.

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

public class wer : MonoBehaviour
{
public Wave[] waves;
public GameObject[] enemy;   // enemy list
private int enemies;
Wave currentWave;
int currentWaveNumber;
int enemiesRemainingToSpawn;
int enemiesRemainingAlive;
float nextSpawnTime;
public Transform[] spawnPoints;

void Start()
{
    NextWave();
}

void Update()
{

    if (enemiesRemainingToSpawn <= 0)
    {
        NextWave();
    }

    if (enemiesRemainingToSpawn > 0 && Time.time > nextSpawnTime)
    {

        if (currentWaveNumber == 1) // WAVE 1
        {
            enemiesRemainingToSpawn--;
            nextSpawnTime = Time.time + 1; // spawn time 1 second
            int spawnPointIndex = Random.Range(0, spawnPoints.Length);
            enemies = Random.Range(0, 1);
            Instantiate(enemy[enemies], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

        }

        if (currentWaveNumber == 2) // WAVE 2
        {
            for (int i = 0; i < enemy.Length; i++)
            {
                enemiesRemainingToSpawn--;
                int spawnPointIndex = Random.Range(0, spawnPoints.Length);
                Instantiate(enemy[0], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
                Instantiate(enemy[1], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

                // enemy [0] = Instantiate 5 times, time between spawn 1 second;
                // enemy [1] = Instantiate 7 times, time between spawn 1.5f second;

            }

        }

    }

} // end update

void NextWave()
{
    currentWaveNumber++;
    print("Wave: " + currentWaveNumber);
    if (currentWaveNumber - 1 < waves.Length)
    {
        currentWave = waves[currentWaveNumber - 1];
        enemiesRemainingToSpawn = currentWave.enemyCount;
        enemiesRemainingAlive = enemiesRemainingToSpawn;
    }

}

[System.Serializable]
public class Wave
{
    public int enemyCount; // Quantity or number of enemy to Instantiate
    public float timeBetweenSpawns;
}

}


texts: Why doesn't it seem to be any development in the field of 3D VR gear, especially with regard to gaming?

texts:
I remember that way back around 1995, there was this big craze with VR in the media, a whole bunch of (mostly mediocre) games labeled as "virtual-reality-interactive-movie (...)" were published. If I recall correctly, the first 3D VR helmet was called VFX-1 and was sold bundled with Descent and some dedicated joystick. I never owned one, and I read just one review which was mostly enthusiastic, but pointed to some weak points, like the eyes getting tired after an hour or so of playing. Then the whole thing basically flickered down and died.

I suppose the main reason it wasn't successful was that the hardware of the day was not powerful enough, the VR gear's design wasn't perfected to make it comfortable and natural to use, and the companies that made it failed to market it successfully. What I can't understand is why isn't there any development in the field today. There is some vr-ish hardware mostly targeted at the consoles (Kinect, Wii remote, TrackIR), but all projects of creating some 3d head-mounted display system seem to be in early infancy, appear once in a trade show somewhere and aren't heard of again.

I think it could work great with head tracking and some of today's shooters, flight sims (trackIR is nice but the movement scale translation is awkward) and other games with an FPP POV. Is there any technological reason why decent vr headgear can't be made today, or is it just that nobody really cares/everyone is scared to repeat the '90s failure?


texts:
How can I use different materials when using the tag for Unity's rich text syntax?

I want to be able to have sprites that are inline with my text without having to create custom fonts.

Here's what I have so far:

Here's the syntax that I'm using for the text in my image:

Planetary <quad material=1 size=20 x=0.1 y=0.1 width=0.1 height=0.1 /> Intergalactic

I'm guessing "material=1" refers to the material index of the Text object. How can I set it to use a different material altogether?

Is there a plugin or other resource that makes embedding icons in text easier?


texts: NavMesh - Changing Mesh by Jumping upwards

texts:
I have been playing around with the NavMesh and I have seen that there are different situations where an agent has to change meshes.

When it works:

Everything seems to work alright with links, if I try to make the agent jump from a mesh to another one, tweaking the "Jump distance" paramenter

Another scenario is when the agent needs to fall to another mesh to reach the target. This one also works, when I tweak the "Drop height" parameter.

When it does NOT work

But there are 2 different scenarios, where the agent cant reach the target. The first one is when the agent must jump upwards instead of dropping.

And the other scenario is when the agent needs to fall to another mesh that is not directly below the one he is standing on.

How could I do so that the agent jumps either to move upwards, or to land in a lower mesh?


texts:
I am developing a game that is being played on a board with the top first tile having the coordinates [0,0], the next one has [0,1], second row has [1,0]... and so on (most likely this would be a standard but im not sure...).

When an object is to move around the board, it should first rotate to a specific angle - meaning if it is moving north North -  it should point to the default angle 0, NE is 45, E is 90, and so on.

How would I get this angle based on where the object is moving, but using 1 formula?

So if an object is to move NW (up and left), on the grid that would mean the destination is [y-1, x-1] in reference to where it is now [y,x] ( [row, column] ).

I know I could use 8 statements and say if destination == [y-1, x-1] then angle = 315, but I was wondering if there is a specific formula for this? Im guessing yes but I never loved trigonometry...


texts: 2 cameras that each player sees through a different one

texts:
Im very new to Networking in Unity 5.
Im trying to bring the finished basis for my 2 player, 1 vs 1, turn-based game I made for local multiplayer (both players on same computer) to an online matchmaking system.

In the game currently (for local), there are 3 cameras.
2 centered on separate canvases for selecting attacks for each player.

that once p1 chooses his attacks and presses continue, the camera is deactivated and the 2nd camera for p2's attacks is activated.
Once p2 presses to continue the 2nd cam is also deactivated

and the 3rd cam is put on, this camera is set on the battle arena and plays out in turns the moves picked by the 2 players through a turn-determining system.

What I want to do for the online is have both canvas cameras activated at the same time and each player to be assigned to a different camera.
So is there a good way i should do this? NetworkView on one of the cams?
Hope I explained the premise enough :P


texts:
I'm a new comer to Unity. In Unity, when I click to main camera in Hierarchy view. I see 6 lines: one blue, one red, one green and three white. I know red/green/white lines for (x,y,z) location but I don't know what the meaning of 3 white lines is.

When I resize scene view I see that white lines change respectively. And at some points, three white line same with three color line as image below:

Please explain for me. Thanks :)


texts:
I found this suggestion on a Stack Exchange site to print out what the current directory is:

File file = new File(".");
for(String fileNames : file.list())
    System.out.println(fileNames);

Basically, when I run a game in Eclipse, I get this:

But when I compile the game and run it, it prints out this (it prints out the stuff that is in the same directory as the JAR file is). Images, and sound are working fine. It's just the XML file that is causing this.

How do I make Java read XML files from res folder like it does for images and sound in Eclipse?

My particular code that loads the XML is at http://pastebin.com/59Nt7Dtd.

Slick2D documentation is at http://www.slick2d.org/javadoc/.


texts: Cube that turns every for example 5 seconds 90 degrees

texts:
I want a cube to rotate 90 degrees every [Second/Counter should be setable]

Like in this video at 3.47 the spiky cube that turns 90 degrees
https://www.youtube.com/watch?v=bxWpsT4lKXU

I have tried to do it but it will not turn 90 degrees smoothly or even 90 degrees, it just turns kind of 90 degrees but I need help I guess.

Here is my script:

public class TurnCubeScript : MonoBehaviour {

public Transform turnCube;

public float turnSpeed;
//SETTING THE COUNTER FOR OBJECT TO TURN
public float setCounter;
public float counter;
//SETTING THE COUNTER TO SETCOUNTER AFTER COUNTER1 = 0
public float setCounter1;
public float counter1;

void Start ()
{
    setCounter = counter + setCounter;
    setCounter1 = counter1 + setCounter1;
}

void Update ()
{
    TurnTheCube();
}

void TurnTheCube()
{

    counter -= 1 * Time.deltaTime;
    if (counter < 1)
    {
        //SOME TRIES...
        //turnCube.transform.eulerAngles += new Vector3 (0, 0, 90 * Time.deltaTime * turnSpeed);
        //turnCube.Rotate(0, 0, 90 * Time.deltaTime * turnSpeed);
        //turnCube.rotation = Quaternion.Euler(0, 0, rotation);

        counter1 -= 1 * Time.deltaTime;

        //GIVES THE CUBE SOME TIME TO TURN
        if(counter1 < 1)
        {
            counter = setCounter;
            counter1 = setCounter1;
        }
    }
}

}


texts:
I have made a cylinder in 3DS MAX. I then added a wave WSM. I then made the animation so it waves a bit. Then exported it to unity.

The animation works perfectly in 3ds max. When I import it to unity the animation does nothing. The cylinder looks fine.

Things I have tried.
Game export,bake animations,embedded files.
Collapse all and collapse alone and nothing happened.
Collapsing to only deforms the cylinder, But the animation still does nothing.

Any idea how to do this?


texts: How much extra processing power is required for a 3D TV compatible game?

texts:
Possible Duplicate:
  How much extra power is required for a stereoscopic 3D game?

How much extra processing power would be required to make a 3D TV compatible mode in a 3D game?

(Nothing specific, think any modern FPS)

Would it be negligible as you would split the framerate between the two 'eyes'?


texts:
When only the main window is created, the fps is able to reach above 1000.However creating 1 more window, resulted in the fps dropping significantly down to about 100. The draw callback draws a blank black screen  and writes the fps onscreen.

Q1) What is the reason behind the sharp drop in fps?
Q2) Any possible ways to improve on this fps?

int main(void){
        int mainwindow,otherwindow1;
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

        glutInitWindowSize(640,480);// set the initial window  size
        glutInitWindowPosition(0,300);//set the initial window position

        mainwindow = glutCreateWindow("main window");
        glutDisplayFunc(Draw);

        glutReshapeFunc(ChangeWindowSize);

        otherwindow1 = glutCreateWindow("Other window");
        glutDisplayFunc(Draw);
        glutReshapeFunc(ChangeWindowSize);

        setVsync(0);

        glutMainLoop();
}

void Draw(){
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    getFPS();

    glutPostRedisplay();
    glutSwapBuffers();
}


texts: Android / IPhone / Desktop C++ Game Template

texts:
I was wondering if anyone has come across any articles detailing how to set up a basic game in C++ for use in Android / IPhone / Desktop applications.

My thoughts just now are that I would like to make my game as a library and have a different project for each device which just interfaces with this library. You know the kind of thing, bootstrap the program, call some library initialize, load and run routines and occasionally pass some information to the library like input. I was hoping someone would have made a template for this kind of thing but I just had no luck finding one.

It seems to me that it's the kind of thing you really only have to do once, so I was hoping someone would have done it for me already.


texts:
using Unity5.5.1f;
using C#;

So I have a circle (2D) divided equally by 16 directions, and I also have a direction V which is different from the other 16.

In order to know which direction is the closest I thought of two apporaches:

Dot product between V and all the other directions and choose the max one
Store atan for all the 16th directions then compute atan for V and see which angle is the closest to V's

My questions are,does anyone know what is the complexity of Mathf.Atan2? Or of an Atan2 algorithm in general? I read it gets worse and worse as the angle becomes bigger, is it true?


texts:
Say we have a player who's walking around in first person perspective. He would like to walk forward, but that would put him inside an object, and that's no good.

Right now what I do is... (pseudocode follows)

class Player(whatever):
  def __move_by(this, displacement):
    for object in scene:
      if(object.hitbox.collides_with(displacement)):
        return #nope.avi
    this.position += displacement

This isn't really good however. Often times I need to watch the console debug output to understand what I would be walking into. Also, not moving at all isn't what happens in "real world" games. I am however in trouble when putting into words, or code, what is it that happens in "real world" games.

What I do with NPCs is calculate the projection of the movement towards their goal along the direction they're heading to, as well as rotating them towards their goal in the process. However, here there's no "goal" distinct from the heading - if we ignore strafing, all the player can do is walk back and forward along his heading exactly.

So... how to handle this?


texts: Preventing rapid inversions of boolean on Collision detection

texts:
I know this is both a strange question and a stupid question. But this is an issue I have dealt with in every single game I've made, and I have yet but to find a solution. I can't be the only one who's run into this problem. My google-fu must suck though, because I can't find any information on how to fix this.

Here's the situation:

A dynamic object is moving in a certain direction.
This dynamic object then hits a static object.
This dynamic object now changes the direction, and heads the other way until it hits an object, and then it changes the direction once again. Kind of like paramecia movement, but not exactly. Seems simple enough.

Now here's the issue. I detect the collision, but I can simply inverse the velocity. Using OOP, I have my own class for this object, which performs all movement and actions. So, instead, I have a boolean in this class. A simple boolean that asks whether I'm moving left. If I am, my velocity is negative. I may also need to flip the sprite. If, however, the boolean is false, my velocity is positive. So, all is fine and dandy.

Now, here is where the common issue comes in. I detect collision, and inverse the boolean(object.movesLeft != object.movesLeft). This is performed EVERY time it detects a collision. The issue now comes in. I inverse the boolean and start to move it in the opposite direction; however, it is not quick enough, and before it gets moving, it still detects the collision, reversing the boolean once again, turning in back into its original value.

I have yet to find a good solution to this. I have found workarounds, but often times I still get this issue.

Currently, I am using Box2D for collision detection, so my flexibility for solutions are constrained. Box2D provides a method for when specific collisions are happening, and when the specific collisions end. I tried only changing the boolean when a collision ends, but there was a pretty big issue. It would only run when a collision ended, obviously. It didn't have to be the moving object that I'm trying to inverse, it could be any dynamic object. The obvious issue is that I need some kind of collision to end before the object will inverse the direction.

So anyways, this is the issue I have faced in even simple games such as pong, and really, really need to find a way to solve it. I can't be the only one of us who have run into this issue.

If anybody understands the issue I'm having, or has experienced it themselves, and has a solution, help would be greatly appreciated. Thanks in advance.


texts:
I am quite new to game development, so here is a question (maybe a stupid one):

In my sidescroller i have a bunch of different graphics objects that i need to draw (player, background tiles, creatures, projectiles etc). Most tutorials i've read so far show that each object has its own draw method, which is then called from some other method.

What if I had one method that does all the drawing? Lets say i keep all my objects in an array or queue (or multiple arrays) and then go through each of them, get an image and draw it.

So basically would it be better (and why) to have each object have its own draw method or one method that does all the drawing? Or does it matter at all? I feel like the second option is more comfortable, because then all the stuff to do with drawing would be in one place...


texts: Cram search results into viewport (of a search minimap)?

texts:
I'm no coder, nor do I try to be. I just had one of those "it's impossible" arguments with folks who love to argue with me before they even understand what the argument is about :)

So I need to know how doable it is and the level of complexity on scales of: Noob LVL to Mediocre to Never-got-laid mad coding skills.

Normally the way people do this is by scaling. But I don't need to preserve the position ratios between objects. What I want to do is = IF the view-port cannot fit all results BUT has space to fit them - juts get them in there (position ratios be damned).

Basically the way I want to do it is the way you would do it in a crowded bar table. Just cram it in. Obviously the other objects move if they are in the way - but if there is space - they fit. (for instance the top orange star has moved down because the blue star was crammed in from outside the view port.

What I'm looking for is an overview explanation about how someone would go about such a thing and how hard it is. I'm pretty sure there is math for that sort of thing - but it's not really an area where i shine... So you don't really need to get into complexities.

Q? Why don't I care about accurate position ratios and directions?

A: Objects in the view port are intractable on click. Representing them displaced from their true positioning is irrelevant so long as you get to interact with them via their functionalities.


texts: Non-rectangular collision detection in Python and Pygame

texts:
I am programming a ray tracer in python, and I have gotten as far as making a character that can move across a 2d plane and change direction of movement when needed. The problem is this: I want to be able to use an image with transparency as the maze that the player travels through, and use transparent parts as parts that aren't walls, where as every thing else is a wall. The way I am using collision detection is by using the "pygame.sprite.spritecollide" method, which takes in a Sprite, and a Sprite Group. So I first add the map sprite object to the group, and then in the main while loop, it checks for collision. Here is a small snippet of what that might look like:
map = Map("map1.png") # "Map" class is regular sprite class but with "image" and "rect"
group = pygame.sprite.Group()
group.add(map)
# inbetween stuff would be here
# while loop \/
running = True
while running:
    # event handling stuff would be here
    if pygame.sprite.spritecollide(player, group, False):
        print True
    # screen drawing routines would be here

As I mentioned, the image has transparency. But never the less, the image rect sticks to the non transparency position that it was, so i have to move the player off screen to get the console to stop saying "True".
So what I ask, is there a way that I can check for sprite collision but with transparency?


texts: Is it ok to return a call to itself inside a method that has a return type?

texts:
Hello all I am making a little blackjack game in Unity. Although these classes don't actually use Monobehaviour or anything just yet.

I have this method and I'm not sure it will work like this or not. I need a way for it to return the card, but if the card has already been dealt out it needs to just repeat until it finds a card that isn't already dealt to return to the original place where i invoke this method from.

    public Card TakeRandomCardFromDeck()
{
    var rand = new Random();
    int randomIndex = rand.Next(cards.Length);
    Card card = cards[randomIndex];
    if (card.stillInDeck)
    {
        cards[randomIndex].stillInDeck = false;
        return card;
    }
    else
    {
        return TakeRandomCardFromDeck();
    }
}

Im specifically worried about the else{ ....... part.

NOTE: I have already done this and whilst it seems to work, its hard to tell whether its actually ran into a card that is already dealt yet since I only have a few cards dealt so far. (I've ran it dozens of times and not had any errors in the one test deal it performs on each run)


texts: What's the best way to keep battle log in a browser based game written in PHP?

texts:
I've searched for it, but I couldn't find any question about this.

I'm working on a game where PvP fights are possible. The game is written in PHP/MySQL.

What I want to implement is to save all the actions of users in the fight (hits, misses, critical hits etc.).

However, I couldn't decide how and where to keep them. As an array, xml file, in json format; in a log file, in the database or in a separate cookie? Which way is the best practice?


texts: Switch beetween Screen on LibGdx application

texts:
i have set main class like this:

public class MyClass extends Game {
    MenuClass menuClass;
    ActionGame actionGame;

@Override
public void create() {
         menuClass = new MenuClass(this);
         actionGame = new ActionGame(this);
         setScreen(actionGame);
    }
}

and method of ActionGame class like this:

....
@Override
public void pause() {
    game.setScreen(game.menuClass);
}

@Override
public void resume() {
    this.show();
    this.render(Gdx.graphics.getDeltaTime());
}
....

and method of menuClass.java like this, when touch Play button:

....
@Override
public void resume() {
    game.actionGame.resume();
}
....

When i touch play button i wish that actionGame class return in action render, but the render don't start. I have try with setScreen, but this restart my screen, this not good. Help

Thanks


texts: AddFontMemResourceEx and D3DXCreateFont corruption

texts:
I'm trying to load a font from a buffer using AddFontMemResourceEx and then creating a D3D font with D3DXCreateFont. This works fine on every platform except Windows XP, where it causes the wrong glyphs to be rendered.

Here's the relevant code (modified slightly for brevity):

char* fontName = "FontName";

HANDLE hFont = AddFontMemResourceEx(data, size, 0, &loaded);

if(!hFont || !loaded) {
    //error handling
}

HRESULT res = D3DXCreateFont(device, 30, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
    ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontName, &font);

if(res != S_OK) {
    //error handling
}

...some code later...
//DrawTextA/W, makes no difference to the result
font->DrawTextW(NULL, message, -1, &rect, DT_LEFT | DT_NOCLIP, colour);

Here's an example render:

Interestingly, if I make a small change to the code to save the font to disk and then reload it with another API function, everything works fine:

char* fontName= "FontName";
char* fileName = "FontName.otf";

FILE* file = fopen(fileName, "w+b");
fwrite(data, size, 1, file);
fclose(file);

//non-ex version works fine too
AddFontResourceEx(fileName, FR_PRIVATE, 0);

HRESULT res = D3DXCreateFont(device, 30, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
    ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontName, &font);

if(res != S_OK) {
    //error handling
}

...some code later...
//DrawTextA/W, makes no difference to the result
font->DrawTextW(NULL, message, -1, &rect, DT_LEFT | DT_NOCLIP, colour);

One caveat is that if the FR_NOT_ENUM flag is specified, even loading from file will result in the same problem. According to the documentation, this flag is implicitly set when using AddFontMemResourceEx.

  A font that is added by AddFontMemResourceEx is always private to the process that made the call and is not enumerable.

It seems this is possibly a bug in XP's API or just poor documentation that's leading to misuse (that happens to work on newer platforms).

Is there something I've missed?


texts: How can I cycle through sprites when the player touches some UI element?

texts:
if(Input.GetKey("y")){
        gameObject.GetComponent<SpriteRenderer>().sprite = Characters[0];

    }
    if(Input.GetKey("u")){
        gameObject.GetComponent<SpriteRenderer>().sprite = Characters[1];
    }
    if(Input.GetKey("i")){
        gameObject.GetComponent<SpriteRenderer>().sprite = Characters[2];
    }

This is my current script, which changes character at keypress Y, U, and I. However as I am developing for touch, I want them to change when a box at the screen is pressed (Left one):

How can I proceed with this? Can I set the sprites to numbers, and let's say at button press, it adds +1, and that changes the sprite? And if so, how does the last one work to get it back at 0?
Appriciate all answers. :)


texts:
I'm trying to learn how to use VertexBuffers in XNA 4.0. I can render wireframe shapes and I can render textured shapes. However, I'm having some trouble rendering them both at once.
 I'm initializing the buffers like this:

vertexBuffer1 = new VertexBuffer(graphics.GraphicsDevice, vertexDeclarationWireframe, numPointsWireframe, BufferUsage.None);
vertexBuffer1.SetData<VertexPositionColor>(pointList1);

vertexBuffer3 = new VertexBuffer(graphics.GraphicsDevice, vertexDeclarationTexture, numPointsTexture, BufferUsage.None);
vertexBuffer3.SetData<VertexPositionTexture>(pointList3);

The above code fails during Draw() because the vertex buffers are using two different types of vertexDeclarations, one for wireframe (VertexPositionColor) and one for textures (VertexPositionTexture). I tried moving the call to VertexBuffer.SetData() to just before the relevant geometry is drawn but that didn't work.

I've also tried setting my Effect object TextureEnabled = false when wireframe is being rendered and resetting it when the textured geometry is rendering, but that didn't work either. The effect seems to be expecting a TextureCoordinate regardless.

What's the proper way to do this?


texts: How do I render to a texture loaded from a PNG file using SDL2

texts:
I'm trying to create a simple 2D game using C++ and SDL2.

I thought it would be a good idea to go for a "layered" rendering model.

I would render my background first, then the world, then the constructs (things like building etc.), then the objects (NPC's etc.) and lastly a toggle-able debug-overlay.

Right now I'm just trying to render a background and a debug overlay but I've hit a wall.

I can't seem to be able to render my debug-overlay on top of my background.

I've set blending mode to SDL_BLENDMODE_NONE for the background and SDL_BLENDMODE_BLEND for the debug overlay.

The problem is however, that my background is loaded from a PNG file, but when calling SDL_CreateTextureFromSurface() the texture access is set to SDL_TEXTURE_ACCESS_STATIC. (Which can't be used as a target if I understand correctly).

My question is: How can I circumvent this issue? How can I make my background "drawable"?

EDIT: Grammar


texts: How can I check for key releases between keyReleased callbacks?

texts:
Slick2D's Input class has a isKeyPressed() method that returns a boolean value according to whether the specified key has been pressed.  I want to check if a key has been released in the same fashion.

I looked into adding a KeyListener to the input object, and overriding the keyReleased() method.  However, because I am currently handling input in the update() method of my BasicGame, this would fracture my code by handling input in two different places, which I'd like to avoid.


texts:
I am working on a particle simulation where we have a lot of spheres which can have different radii. Using this tutorial http://mmmovania.blogspot.de/2011/01/point-sprites-as-spheres-in-opengl33.html (see also code below) I was able to create a sphere from a point, but they all have the size from glPointSize(). Is it possible to extend this with a radius?

#version 330
out vec4 vFragColor;

uniform vec3 Color;
uniform vec3 lightDir;

void main(void)
{
    // calculate normal from texture coordinates
    vec3 N;
    N.xy = gl_PointCoord* 2.0 - vec2(1.0);
    float mag = dot(N.xy, N.xy);
    if (mag > 1.0) discard;   // kill pixels outside circle
    N.z = sqrt(1.0-mag);

    // calculate lighting
    float diffuse = max(0.0, dot(lightDir, N));

    vFragColor = vec4(Color,1) * diffuse;
}

Maybe of interest: I am using #version 120 for my shaders.
Or, is there a better way to do this?

So, combining the two answers I now have:

void
Draw::setGeometry(float* geometry, float* velocity, float* radius, GLuint size){
    this->_size = size;

    glGenBuffers(1, &_vertexData);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexData);
    glBufferData(GL_ARRAY_BUFFER, _size * 3 * sizeof(float), geometry, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &_velocityData);
    glBindBuffer(GL_ARRAY_BUFFER, _velocityData);
    glBufferData(GL_ARRAY_BUFFER, size * 3 * sizeof(float), velocity, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &_radiusData);
    glBindBuffer(GL_ARRAY_BUFFER, _radiusData);
    glBufferData(GL_ARRAY_BUFFER, size * sizeof(float), radius, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

}

And the drawing method:

void
Draw::paint(GLenum mode){
    glBindBuffer(GL_ARRAY_BUFFER, _vertexData);
     glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(mode, 0, _size * 3 * sizeof(float));
    glDisableVertexAttribArray(0);
}

And the Vertex Shader:

#version 130

attribute vec3 position;
attribute vec3 velocity;
attribute float size;

uniform mat4 MVP;
uniform mat4 MV;

void main(){
   gl_PointSize = size;

   gl_Position = MVP * vec4(position, 1.0);
}

The problem is that when gl_PointSize = 15 is set, they are drawn well. When I make it equal with size, then it looks like this: http://picpaste.com/Big_particles-daIBnJCG.png

Works better now. Particles still getting bigger as they move along.


texts: Is it worthwhile to use particle pools in managed languages?

texts:
I was going to implement an object pool for my particle system in Java, then I found this on Wikipedia. To rephrase, it says that object pools aren't worth using in managed languages like Java and C#, because allocations take just tens of operations as compared to hundreds in unmanaged languages like C++.

But as we all know, every instruction may hurt game performance. For example, a pool of clients in an MMO: the clients won't enter and exit the pool too fast. But particles may get renewed tens of times in a second.

The question is: is it worth it to use an object pool for particles (specifically, those that die and get recreated fast) in a managed language?


texts: C++ read access violation when deleting object

texts:
In my game, I've created (likely a very bad) Entity Manager that handles all entities in my game. It will assign random ID's to these entities and then add them to a map:

player = new Player(entityManager);
player->SetPosition(S2D::Vector2(50, 250));
entityManager->AddEntity(player);

//Adds entites to a list and assigns a random ID to them
void EntityManager::AddEntity(Entity* entity)
{
    int ID = rand();
    for(int i = 0; i < IDS.size(); i++)
    {
        if(IDS[i] == ID)
        {
            ID = rand();
            i = 0;
        }
        else
        {
            break;
        }
    }

    entity->SetID(ID);
    entities.insert(pair<int, Entity*>(ID, entity));
}

Each of these entities has a Update and Render function that is ran by the Entity Manager through it's Update and Render functions which are called by the Game Loop:

void EntityManager::Update(float deltaTime)
{
    if(!entities.empty())
    {
        //Removes entities that need to be deleted
        for(int i = 0; i < toDeleteEntities.size(); i++)
        {
            RemoveEntity(toDeleteEntities[i]);
            toDeleteEntities.erase(toDeleteEntities.begin() + i);
        }

    //Runs the Update function of all entities and adds Entites that need to be deleted to a list
        for(const auto entity : entities)
        {
            if(entity.second->ShouldDestroy())
            {
                toDeleteEntities.push_back(entity.second);
            }

            entity.second->Update(deltaTime);
        }
    }
}

void EntityManager::Render()
{
    if(!entities.empty())
    {
        for(const auto entity : entities)
        {
            entity.second->Render();
        }
    }
}

As well as looping through each entity, the Update function also loops through a vector called "toDeleteEntities" which contains entities that are to be deleted. Each Entity has a boolean called "Destroy" and if it's set to true, the Update function in the Entity Manager will add that entity to the vector.

//Runs the Update function of all entities and adds Entites that need to be deleted to a list
    for(const auto entity : entities)
    {
        if(entity.second->ShouldDestroy())
        {
            toDeleteEntities.push_back(entity.second);
        }

        entity.second->Update(deltaTime);
    }

Then before that for loop, the Update function will run this for loop that will remove each entity from the "toDeleteEntities" vector and then pass it onto another function that will delete it:

//Removes entities that need to be deleted
    for(int i = 0; i < toDeleteEntities.size(); i++)
    {
        RemoveEntity(toDeleteEntities[i]);
        toDeleteEntities.erase(toDeleteEntities.begin() + i);
    }

That delete function is this:

//Removes an Entity from the Game
void EntityManager::RemoveEntity(Entity* entity)
{
    if(entity->GetID() == -572662307)
    {
        return;
    }

    entities.erase(entity->GetID());
    delete entity;
}

The if Statement is there because of a previous error I had where I believe the for loop would pass the same entity to the delete function twice resulting in it trying to delete a already deleted object. I know it would be better to fix the error but truthfully it's easier to just do that XD.

Anyway hopefully that's enough context, if you need anymore then just ask. So all of this seems to work correctly somewhat with this Gem entity I have, it runs correctly and gets deleted without problems. But I've noticed when I attempt to add new entities and try and delete them, I get this _Pnext error:

And I just can't figure out why. It seems to be coming from this loop here in the xutility class:

Does anyone know why this error is happening?

EDIT
Screenshot of the Call Stack:


texts:
I'm wondering about gpu accelarated physics after reading about Erwin Coumans presentation on GPU accelerated physics: http://www.gdcvault.com/play/1018185/GPU-Rigid-Body-Rigid-Body
(demo video here: http://www.youtube.com/watch?v=ZkF4yMmP0R8)

While it certainly looks like a massive performance boost, I don't have any expirience with gpgpu programming, so I'm wondering how practical this is for games. You'd have to manage communication between the different parts of the game engine. I know there are facilities to have opencl & opengl share memory, that covers the rendering part.. but what about the other parts of a typical game engine? Let's say we have a fixed timestep physics simulation (lets say 60hz) and corresponding game logic (which also runs at 60hz) that needs to act on certain events triggered by the physics engine. Game logic is not necesarily suited for execution on the gpu, it may for example be very branching intensive. This would mean a readback from the gpu to the cpu, wouldn't this create too much latency to have our game logic proceed at 60hz?


texts:
So, I am wanting to use Godot to get a (binary) file using HTTP and then either save it or, even better, turn it into a Resource in memory that I can use.  It'll be WAV files that I'm getting in return (trying to implement MaryTTS, which is running as a server on localhost).  I had a look at the docs for HTTPRequest, but can't seem to get a working solution.

I do $HTTPRequest.request("http://...") when a keypress is made, and I have the _on_HTTPRequest_request_completed() function, but this never seems to be called.  I tried with the function in the same Node as the request (as per the docs' example), and I also tried putting it as part of a script for the HTTPRequest Node.  If I hit the triggering key fast enough, it gives an error ("HTTPRequest is processing a request"), but if I do it slower, it doesn't give that error, so it appears it is finishing.  It just doesn't do anything when it finishes.  HTTPRequest gives a return value of 0, which I assume means no error?  (Or should this give me HTTP status codes?)

Any idea what I'm doing wrong?  Can HTTPRequest handle binary files?  How do I get this working?

(Any suggestions on a better way to implement MaryTTS are also welcome).


texts: How can I merge the corners of fractally-generated borders so they look natural?

texts:
I'm using a fractal generator to generate borders around a rectangular area. It works great, but my problem is with corners.

A naive implementation when the left border overlaps the top border:

Obviously this doesn't look great. I tried averaging the weight of pixels from top and left border... not so great either.

My best shot was with iterating over a circle rather than over a line for corners, sort of like:

for(var i = 0; i < buffer.Length; i+= step) {
  for(var j = 0; j < buffer[(int)i]; j++) {
    PutPixel(Cos(i*CoeffStep)*CoeffRadius*j,
      Sin(i*CoeffStep)*CoeffRadius*j, ColorFor(j));
  }
}

Where PutPixel merges color into average if the pixel is already set.
This however this skips some pixels at higher radii.

Example:

Setting smaller steps obviously helps, but not 100%. Anyone have any ideas what I can do?


texts: OpenGL ES 2.0: Texture does not appear to be correct

texts:
Here are my shaders...

 GLbyte vShaderStr[] = "attribute vec4 vPosition;   \n"
 "attribute vec2 texPosition; \n"
 "attribute vec4 inColor;   \n"
 "varying vec4 fragColor;   \n"
 "varying vec2 v_texCoord;     \n"
 "void main()                 \n"
 "{                           \n"
 "   gl_Position = vPosition; \n"
 "   fragColor = inColor; \n"
 "   v_texCoord = texPosition; \n"
 "}                           \n";

GLbyte fShaderStr[] =
  "precision mediump float;                            \n"
  "varying vec2 v_texCoord;                            \n"
  "uniform sampler2D s_texture;                        \n"
  "void main()                                         \n"
  "{                                                   \n"
  "  gl_FragColor = texture2D( s_texture, v_texCoord );\n"
  "}                                                   \n";

And here is my code...

GLfloat gObj[18] = {
  0.5f, 0.5f, 0.0f,
  -0.5f, -0.5f, 0.0f,
  0.5f, -0.5f, 0.0f,
  0.5f, 0.5f, 0.0f,
  -0.5f, 0.5f, 0.0f,
  -0.5f, -0.5f, 0.0f
}
...
GLuint textureId;

GLubyte bytePix[4 * 3] ={
        255, 0, 0,
        0, 255, 0,
        0,0, 255,
        255,255,0
};
GLfloat texC[] = {
            0.0f, 0.0f,
            0.0f, 1.0f,
            1.0f, 1.0f,
            1.0f, 0.0f
    };
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, bytePix);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, gObj);
glVertexAttribPointer(textCoordLoc, 2, GL_FLOAT, GL_FALSE, 0, texC);

glUniform1i(sampler, 0 );
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(textCoordLoc);
glDrawArrays(GL_TRIANGLES, 0, 6);

But when I run the app I see the following...

This seems wrong, how can I make it so each quadrant of the square is the color in the texture. Of course I could always be misunderstanding textures in general.


texts:
I have component Renderer, that Draws Texture2D (or sprite)
Then I have method OnUpdate, and there should be my rendering code, something like

spriteBatch.Draw(Texture, Vector2.Zero, Color.White)

But first I need to do spriteBatch.Begin();. Where should i call it? And how can I make sure it's called before any Renderer components OnUpdate method?

(i need to do more stuff then just Begin() i also need to set right rendertarget for camera etc.)


texts:
I'm working on a simple multiplayer online game. and I use UNET and Networkmanager.

In my game I have some rooms and players that they can join to this rooms by connecting to specific server.exe file that I runned on a dedicated server.

My problem is when I use port 7777 for first server, if I run another server, then this error Appear :

  Cannot open socket on ip{*},and port{7777}

For now I solved this issue by building servers with specific ports.
for example in server1.exe I used port 7777 by default.
and server2.exe , 7778 and same for other servers .

But I want to do this automatically. I mean when the server recognize port 7777 is busy , then increase port number.

I want to know can I use try catch for this kind of errors ?
because I used try catch but it's not work.
I don't know how to use it. this is part of my code :

try
    {
        StartServer();
    }
    catch(Exception ex)
    {
        networkPort++;
        //then change port number and run server again
    }

I just looking for a way that my servers run by choosing right port automatically.


texts: Why moving platform script is not working?

texts:
I have some code attached to a moving platform:

public Transform pos1, pos2;
public float speed;
public Transform startPos;

Vector3 nextPos;
// Start is called before the first frame update
void Start()
{
    nextPos = startPos.position;
}

// Update is called once per frame
void Update()
{
    if (transform.position == pos1.position)
    {
        nextPos = pos2.position;
    }
    else if (transform.position == pos2.position)
    {
        nextPos = pos1.position;
    }
    transform.position = Vector3.MoveTowards(transform.position, nextPos, speed * Time.deltaTime);
}

private void OnDrawGizmos()
{
    Gizmos.DrawLine(pos1.position, pos2.position);
}

But my platform does not go to the pos2 when it reaches the pos1. What is wrong here?


texts:
Okay, so I think I need to use a tween in order to move an object in my game.  I have some little green dudes that need to move in an arc (bezier) to a location that is clicked by the user.  My game functions by having the mouse point raycast to the screen giving my character a position to move to.  They don't just run though,  they fire off their jetpacks and should travel in an arc to the target position.  I'm pretty new to Unity but all I can come up with is using a tween to do this.  Am I missing something?   That being said,  I'm totally confused on what a tween actually is.  I can't wrap my head around how the object can be moved outside of an update function.  I'm using the "free from the asset store" LeanTween package.  I feel like there should be some sort of easier way to achieve the desired behavior.

How can I have my character move from Vector3 A to Vector3 B in an arc?


texts: How do I cover a plane in a bumpy foam material effect?

texts:
I need to fill a weapon bag with foam material.

This is what it should look lik:

The material in the upper part of the bag looks like this:

I'm using HDRP.

How could I do this?

Thank you!

Edit: I have played around with Parallax Occlusion mapping, and I got this result.

Edit2: I am not sure if I use the Pixel Displacement as it has been suggested to me.

Also, I'm not sure if I use it the correct way:

I have created a Height map and put it into the Height map slot.
This doesn't create any effect.
I have to put the same map into the Base map slot in order to see the effect.
If I put a black image into the Base map slot or if I choose Black as the Base color, no effect is visible.

I don't understand why this is so. I think even if my Base map is black, the Shader has pixels that it can move.

This is my height map:

Edit 3: It was suggested that I should use a normal map. This doesn't look at all what I expected. The normal map was created from the Height map using an online tool:

By Philipp's answer I found out that the normal map alone is not enough.