texts: What is a good algorithm for generating a linear regression of positions in 3D space? (for getting the direction of a thrown object in VR)

texts:
I'm trying to get throwing to feel right in my VR game. I don't plan on actually using physics to do this; my idea is to accurately determine the lateral direction of the throw, then move the object in the intended direction (with a doctored Y value) at a speed dependent on other factors.

The language of the code doesn't matter too much, but I'm using Godot, so something that wouldn't require me to import a bunch of different math libraries (by converting them to Godot's Python-style GDScript) would be ideal. It doesn't need to be robust.

To give you an idea of what I was thinking, my original plan was to save the position of the grabbing controller every frame while an object is being held, removing old positions if the controller is moving backwards, then averaging out the movement deltas over the last 10 or 15 frames or so before letting go (it should be consistent since Godot has a fixed-timestep "update" function available) and normalizing the vector to get the direction the object should travel in.

However, this blog post got me thinking that spending the time learning how to do the linear regression in a more robust way, then applying that to 3D/VR, might be worthwhile. I just wonder if, since I don't need the actual linear or angular velocity, it might be overkill in terms of time spent on the feature.


texts: Build Unity3D project from source without Unity Editor

texts:
I am trying to create an installer which will download the source of the latest release of a Unity project from a repository hosted on Github and then build it into an executable file. I have tried looking online for a solution, but, they all require the Unity Editor to be installed.

Is it possible to build a Unity project from the source code into a .exe file or a .dmg file without the Unity Editor?

EDIT: From @DMGregory's answer, it seems that using an external tool to build Unity Projects will violate Unity's Terms of Service. Therefore, I am updating the question.

Does Unity provide a lightweight (installer) tool that can allow clients to build and install Unity projects from source rather than requiring the client to install the entire Unity Editor?


texts: Horizontal lines between vertices do not render

texts:
Good day,

I am using LibGDX to try to render a mesh for a hexagon board. I can render the triangles, which is great, but I am having an issue rendering all of the line segments for the mesh and I can't figure out why.

Pictures

Here is an image of what it renders with the primitive type set to GL_TRIANGLES. The colours are just to help me troubleshoot/identify which triangles are where.

.

Here is an image of what it renders with the primitive type set to GL_LINES. Whether there is 1 triangle being rendered or 1 million, the horizontal lines do not get rendered.

.

Code

How I create the mesh:

mesh = new Mesh(true, MAX_VERTS, 0,
                new VertexAttribute(Usage.Position, POSITION_COMPONENTS, "a_position"),
                new VertexAttribute(Usage.ColorUnpacked, COLOR_COMPONENTS, "a_color"));

mesh.setVertices(verts);

renderable = new Renderable();
renderable.mesh = mesh;
renderable.primitiveType = GL20.GL_TRIANGLES;
renderable.meshPartSize = mesh.getNumVertices();
renderable.meshPartOffset = 0;

When I switch the renderable.primitiveType to GL20.GL_LINES I get the 2nd picture from above.

I've tried to set the renderable.meshPartSize a couple of different ways:

renderable.primitiveType = GL20.GL_LINES;

renderable.meshPartSize = mesh.getNumVertices(); // Doesn't work
renderable.meshPartSize = MAX_VERTS * 2;         // Doesn't work

Here is how I make a triangle:

void drawTriangle(float x, float y, float z, float width, float height, Color color) {
    // Counter-clockwise winding

    // Vertex 1: Top Left
    verts[idx++] = x;
    verts[idx++] = y;
    verts[idx++] = z;
    verts[idx++] = color.r;
    verts[idx++] = color.g;
    verts[idx++] = color.b;
    verts[idx++] = color.a;

    // Vertex 2: Bottom Left
    verts[idx++] = x;
    verts[idx++] = y;
    verts[idx++] = z + height;
    verts[idx++] = color.r;
    verts[idx++] = color.g;
    verts[idx++] = color.b;
    verts[idx++] = color.a;

    // Vertex 3: Top Right
    verts[idx++] = x + width;
    verts[idx++] = y;
    verts[idx++] = z;
    verts[idx++] = color.r;
    verts[idx++] = color.g;
    verts[idx++] = color.b;
    verts[idx++] = color.a;
}

Any help would be appreciated.

Thanks.


texts:
How do i render my game scene into an imgui window?

I want to get from this:

to this :


texts: How to convert applied torque or angular velocity angle to a positive 0 - 360 degree?

texts:
Objective

To convert body.getAngle() to 4 direction (NSEW), when torque or angularvelocity is used

Because box2d body default angle is zero, I used it as reference to create my character direction. 0 degree means West, 90 degree North, 180 degree East and 270 is south, with a range of 45 degree. When I manually transform the body I get the right direction, but when I use the body.setAngularVelocity() or body.applyTorque() I get a different angle, which is more than 360 degree, assume  body.angle() * RADIAN_TO_DEGREE. I am only expecting 0 to 360 degree without negative.

public static SteerDirection getDirection(float degreeAngle) {
    SteerDirection direction = SteerDirection.NONE;
    if(degreeAngle > 0 && degreeAngle < 22.5 || degreeAngle > 337.5 && degreeAngle < 360){
        direction = SteerDirection.WEST;
    }

    if(degreeAngle > 22.5 && degreeAngle <67.5) {
        direction = SteerDirection.NORTH_WEST;
    }

    if(degreeAngle > 67.5 && degreeAngle < 112.5){
        direction = SteerDirection.NORTH;
    }

    if(degreeAngle > 112.5 && degreeAngle < 157.5){
        direction = SteerDirection.NORTH_EAST;
    }

    if(degreeAngle > 157.5 && degreeAngle < 202.5){
        direction = SteerDirection.EAST;
    }

    if(degreeAngle > 202.5 && degreeAngle < 247.5){
        direction = SteerDirection.SOUTH_EAST;
    }

    if(degreeAngle > 247.5 && degreeAngle < 292.5) {
        direction = SteerDirection.SOUTH;
    }

    if(degreeAngle > 292.5 && degreeAngle < 336.5) {
        direction = SteerDirection.SOUTH_WEST;
    }

    return direction;
}


texts: Forcing Proportion Lock on Layout Element

texts:
I'm trying to develop a Card-Game in Unity3D using 2D mode.

Every Card GameObject on my Scene contains a Layout Element Component with following parameters:

The parent container, a Panel has a Horizontal Layout Group Component with this settings:

Now i have this parent control multiply times on my Scene with different sizes. But now its destroys the proportions of my Card, as you can see below on the screenshot.

So is there a way to ensure the proportions of my Card when scaling or shrinking the parent Panel?


texts:
I have a list of rotations (on a cube in 3d space with the y-Axis pointing upwards, x-Axis pointing righthand and z-Axis pointing towards you) for example

+90 deg around x-Axis followed by
+90 deg around y-Axis followed by
+90 deg around y-Axis followed by
-90 deg around x-Axis

All rotations are only of type (+- 90 deg around x / y). The list can be of any length. My goal is to break it down to only three operations. I can't figure out how to calculate the three arguments xDeg,yDeg,zDeg which i can apply in the same order to rotateX,rotateY,rotateZ to get the same result as applying the complete list one after another to the rotation-functions. i tried to build up a permutation matrix depending on the actual position in the list of rotations when i iterate over it to apply the current deg value of a list item to either xDeg,yDeg,zDeg. I couldn't make ist work.

var gTrans = (function() {

  var perm = [[1,0,0],[0,1,0],[0,0,1]];
  var set = [0,0,0];

  function rotateUp() {
    //set = math.chain(set).add(math.multiply(perm,[-90,0,0])).done();
    //set = math.chain(set).add([-90,0,0]).multiply(math.transpose(perm)).done();
    perm = math.multiply([[1,0,0],[0,0,1],[0,-1,0]],perm);
    set[0] -= 90;
  }

  function rotateDown() {
    //set = math.chain(set).add(math.multiply(perm,[90,0,0])).done();
    //set = math.chain(set).add([90,0,0]).multiply(math.transpose(perm)).done();
    perm = math.multiply([[1,0,0],[0,0,-1],[0,1,0]],perm);
    set[0] += 90;
  }

  function rotateLeft() {
    //set = math.chain(set).add(math.multiply(perm,[0,-90,0])).done();
    //set = math.chain(set).add([0,-90,0]).multiply(math.transpose(perm)).done();
    perm = math.multiply([[0,0,-1],[0,1,0],[1,0,0]],perm);
    set[1] -= 90;
  }

  function rotateRight() {
    //set = math.chain(set).add(math.multiply(perm,[0,90,0])).done();
    //set = math.chain(set).add([0,90,0]).multiply(math.transpose(perm)).done();
    perm = math.multiply([[0,0,1],[0,1,0],[-1,0,0]],perm);
    set[1] += 90;
  }
})();

The code above is written with javascript, p5js and mathjs libs. Does someone have an idea? I know it's possible to simply multiply the rotation matrices. But i need the angles and the informations if it's 750 deg (not only 750 mod 360 deg).


texts: Why does my machine render OpenGL using my onboard chipset instead of my graphics card?

texts:
I'm following an OpenGL tutorial series at opengl-tutorial.org, but have run into a problem:

The following lines:

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

cause my glfwCreateWindow() call to return null.

As I understand, this is caused by lack of support for OpenGL 3.3.

Why is my machine trying to render OpenGL 3.3 using my onboard graphics chipset (Intel HD Graphics 3000, which only supports OpenGL 3.1) instead of using my dedicated graphics card (GeForce 520M, which supports OpenGL 4.x)? I think this has something to do with power saving.

Note: I have newly updated nVidia drivers, installed as of yesterday. I know they are working because if I right-click my desktop I get a context menu for nVidia Control Panel.

Running OpenGL Extensions Viewer 4.x also displays that I'm using Intel HD Graphics 3000, supporting OpenGL <= 3.1, which is consistent with my theory regarding power saving.

Regards,


texts: Is there a way of using XNA+Xbox 360 with the current generation of 3D televisions?

texts:
I'm interested in playing around with 3D on a new Sony 3D television (polarized light rather than red/green/blue anaglyph glasses).  Is this possible with XNA on the current XBox 360?

Alternatively, It doesn't look like there is a comparatively trivial PS3 dev. solution to XNA right now, hence my interest in XNA and the 360.

Regards,


texts:
Basically decided to make my own mob, I have:

Created my mob's entity class
Created my mobs model class
Drawn the model
Added the function call for addMapping within the EntityList class

I'm stuck on what to do next. I've tried finding the code that deals with passive animal spawning in the world, however I can't seem to find it.

Help greatly appreciated.


texts: What are the technical reasons that make it difficult for a game to be maximized in windowed mode?

texts: I am curious as to why most games do not have a mode in which you can easily move your cursor outside the game window to another monitor for example? World of Warcraft maximized window does this really well. Does anyone have any insight on why this would be difficult and/or not worth it for most games to implement?


texts:
I am developing a mobile game for Android. It is a 3D jumping game (like ski jump) where wind plays a important role so i need to simulate it. How could I achieve this?

The game uses libgdx for rendering and a port of Bullet physics engine for physics. To simulate the jump I have 2 spheres which are placed at the start and at the end of the player and gravity is applied to them (they role down the hill and jump at the end). I use them to calculate the angle and the position of the player. If a button is pressed some extra y speed is applied to them (to simulate the jump before the end of the jumping ramp).

But now I have to add wind to it. How is this usually done? Which collision box/method should I use? The way I understand it I only have to apply some force with direction to the player while in mid air. How can I do this in Bullet?


texts:
I was wondering what peoples approaches or thoughts were on automating performance testing in XNA. Currently I am looking at only working in 2d, but that poses many areas where performance can be improved with different implementations.

An example would be if you had 2 different implementations of spatial partitioning, one may be faster than another but without doing some actual performance testing you wouldn't be able to tell which one for sure (unless you saw the code was blatantly slow in certain parts). You could write a unit test which for a given time frame kept adding/updating/removing entities for both implementations and see how many were made in each timeframe and the higher one would be the faster one (in this given example).

Another higher level example would be if you wanted to see how many entities you can have on the screen roughly without going beneath 60fps. The problem with this is to automate it you would need to use the hidden form trick or some other thing to kick off a mock game and purely test which parts you care about and disable everything else.

I know that this isnt a simple affair really as even if you can automate the tests, really it is up to a human to interpret if the results are performant enough, but as part of a build step you could have it run these tests and publish the results somewhere for comparison.

This way if you go from version 1.1 to 1.2 but have changed a few underlying algorithms you may notice that generally the performance score would have gone up, meaning you have improved your overall performance of the application, and then from 1.2 to 1.3 you may notice that you have then dropped overall performance a bit.

So has anyone automated this sort of thing in their projects, and if so how do you measure your performance comparisons at a high level and what frameworks do you use to test? As providing you have written your code so its testable/mockable for most parts you can just use your tests as a mechanism for getting some performance results...

=== Edit ===

Just for clarity, I am more interested in the best way to make use of automated tests within XNA to track your performance, not play testing or guessing by manually running your game on a machine. This is completely different to seeing if your game is playable on X hardware, it is more about tracking the change in performance as your game engine/framework changes.

As mentioned in one of the comments you could easily test "how many nodes can I insert/remove/update within QuadTreeA within 2 seconds", but you have to physically look at these results every time to see if it has changed, which may be fine and is still better than just relying on playing it to see if you notice any difference between version. However if you were to put an Assert in to notify you of a fail if it goes lower than lets say 5000 in 2 seconds you have a brittle test as it is then contextual to the hardware, not just the implementation. Although that being said these sort of automated tests are only really any use if you are running your tests as some sort of build pipeline i.e:

Checkout -> Run Unit Tests -> Run Integration Tests -> Run Performance Tests -> Package

So then you can easily compare the stats from one build to another on the CI server as a report of some sort, and again this may not mean much to anyone if you are not used to Continuous Integration. The main crux of this question is to see how people manage this between builds and how they find it best to report upon. As I said it can be subjective but as knowledge will be gained from the answers it seems a worthwhile question.


texts:
I want to develop a flash game. It would draw a stick man, and edit his pose.

I think what I need to learn are bones animation and physics engine.

Can anyone introduce some good resources to learn both?


texts: Should I use one line per .wav or one scene per .wav for character speech?

texts:
I'm building a game in XNA and I wanted to know how I would organize the character speech portions of the game. These would include both cutscenes and anything else where characters interact.

I wanted to know if it would be more efficient to use sound file (.wav) per character line, such as:

SCENE 4: ENTERING THE CAVE

PLAYER1: Wow, this is going great! } One file called "04_PLAYER1_01.wav"
PLAYER2: I know! } A file called "04_PLAYER2_01.wav"
PLAYER1: Let's get going! } A file called "04_PLAYER1_02.wav"

I wanted to know if that would be better opposed to:

SCENE 4: ENTERING THE CAVE

PLAYER1: Wow, this is going great! }
PLAYER2: I know!                   } One file called "scene_04.wav"
PLAYER1: Let's get going!          }

I am aware that by going with option 2, you'd probably save a bit more space because you have less files (but they might be larger) but it poses the problem of coordinating it all.

I was thinking maybe XML for coordinating the speech and cutscenes, but am open to other suggestions. :)

P.S. This not intended to be a "DIALOG-TREE". These are actual models moving their lips in accordance with sound!


texts: Floating point determinism with respect to procedural generation, clustering and GPU offloading

texts:
I've been designing a distributed procedural generation system for a while now in my spare time and one of the problem's I've been thinking about recently, with respect to the broader architecture, is that of floating point determinism inconsistency when you can't ensure that you have a homogeneous cluster of machines running a persistent world.

Part of my design requires that any given machine can regenerate procedural content as needed, allowing for unimportant but resource-hungry content to be destroyed and recreated as needed on whatever machine is available to do the work.

I have been running on the basic idea that I will use high-precision 32/64 bit integers for most things, and that generally works fine, but the standard coherent noise algorithms all use floating point values in their calculations.

Do I need to implement custom non-floating-point versions of all those algorithms (i.e. using longs) or is there a better approach?
Should I be using fixed-point types for this kind of thing, and if so, how does that impact my desire to have the option to offload some of the PCG work to the GPU, when possible? Also, are fixed point types fast enough for heavy use within a game engine?
Can I ignore floating point precision issues if I can get away with a maximum level of precision? i.e. If I'm happy to use no more than, say, six decimal places of a result, does that keep me safe across different machines and architectures?

Note: my engine is purely the simulation side of things. It doesn't matter to me if there are slight rendering inconsistencies when a user is playing the game; all that matters is that the procedurally-generated source data is consistently regenerated no matter which machine in a cluster is doing the work.


texts: The camera in a 2D tile based side scroller is moving slower than the player

texts:
In my 2D tile based side scroller, I want a camera that scrolls in the x direction, but not in the y direction. The world is separated into three zones; one on the left and one on the right where the camera doesn't move, and one in the middle where the camera should move left and right and centered on the player.

The world is a 2D int array where each tile has it's own ID (number). The player's position is in pixel coordinates.

My problem is that when the player moves outside the left zone (and into the middle), the camera always move slower than the player, which means the player disappears of the screen. Since I calculate the camera's position from the player position when the player is in the middle zone, I don't understand why the camera isn't always centered around the player.

My code for calculating the camera's position and drawing the background is as follows (in C#):

int worldWidth = world.GetLength(0) * _TILE_WIDTH;
int resX = camera.Width / TILE_WIDTH;
int resY = camera.Height / TILE_HEIGHT;

Bitmap screenBmp = new Bitmap(camera.Width, camera.Height);
Graphics g = Graphics.FromImage(screenBmp);

// upper left corner of the camera in the world
Vector2D pCamera = new Vector2D(p.X + (p.PlayerSize.Width / 2) - (screenBmp.Width / 2), 0);

int oneMoreX_tile = 0;  // draw one more tile off the screen?

if (p.X + (p.PlayerSize.Width / 2) < 0 + screenBmp.Width / 2) // past the left zone
{
    pCamera.X = 0;
}
else if (p.X + (p.PlayerSize.Width / 2) >= worldWidth - screenBmp.Width / 2) // past the right zone
{
    pCamera.X = worldWidth - screenBmp.Width;
}
else  // between the zones
{
    oneMoreX_tile = 1;
}

int xOffset = (int)pCamera.X % TILE_WIDTH;
int yOffset = (int)pCamera.Y % TILE_HEIGHT;

int startX_tile = (int)pCamera.X / TILE_WIDTH;
int startY_tile = (int)pCamera.Y / TILE_HEIGHT;

for (int i = 0; i < resX + oneMoreX_tile; i++)
{
    for (int j = 0; j < resY; j++)
    {
        int tileValue = world[startX_tile + i, startY_tile + j];

        // tile coord in tileset
        int x = tileValue % tilesetWidth_tile;
        int y = tileValue / tilesetWidth_tile;

        // pixel coord in tileset (top left)
        int x_px = x * TILE_WIDTH;
        int y_px = y * TILE_HEIGHT;

        g.DrawImage(tileset,
            new Rectangle(i * TILE_WIDTH - xOffset, j * TILE_HEIGHT - yOffset, TILE_WIDTH, TILE_HEIGHT),
            new Rectangle(x_px, y_px, TILE_WIDTH, TILE_HEIGHT),
            GraphicsUnit.Pixel);
    }
}

This code runs every time the graphics timer ticks. (I'm using Windows Forms..) I have two timers set at the same interval; one graphics timer and one physics timer. The physics timer just updates the player's position.

Regardless of world length, the player always disappears of the screen at 640 pixels (which is also the width of the screen), and the camera's position is 336 pixels from the left. I have also tried with lower speeds with no success.

Please ask if there's anything more you need to know. Any help would be appreciated.


texts: How to pass a big (60+) amount of variables to an HLSL pixel shader?

texts:
I am in trouble at trying to pass a big amount of variables needed for my pixel shader computations.

After trying and failing to link my struct to a cbuffer (data alignement mismatch) I tried passing my variables first to the vertex shader (with an D3D11_INPUT_ELEMENT_DESC / CreateInputLayout) with the intent to link them to the pixel shader through semantics but I hit the 32 shader inputs limit.

I am really stuck (and quite a noob at DX). What is a common / standard way to do this ? Can I only rely on a cbuffer ? Is creating a D3D11_INPUT_ELEMENT_DESC / CreateInputLayout even possible for the pixel shader ?

Example struct I want to pass to my pixel shader :

struct SceneParamsInterface {
    bool DEAOEnabled;
    XMFLOAT4 DEAOColor;
    double DEAOPow;
    bool lightEnabled;
    XMFLOAT4 lightColor;
    XMFLOAT3 lightDirection;
    bool lightMultiply;
    double lightMultiplyFactor;
    bool ambiantLightEnabled;
    XMFLOAT4 ambiantLightColor;
    bool HSEnabled;
    int HSSpread;
    bool fogEnabled;
    XMFLOAT4 fogColor;
    double fogDistanceMax;
    bool glowEnabled;
    XMFLOAT4 glowColor;
    double glowRadius;
    XMFLOAT4 skyColor;
    bool skyBoxEnabled;
    //uniform sampler2D skyBoxTexture;
    int skyBoxScheme0; // top
    int skyBoxScheme1; // left
    int skyBoxScheme2; // front
    int skyBoxScheme3; // right
    int skyBoxScheme4; // back
    int skyBoxScheme5; // bottom
    int skyBoxRotate;
    double skyBoxRotateSpeed;
    XMFLOAT3 skyBoxRotateAround;
    bool orbitTrapsEnabled;
    int orbitTrapsId;
    XMFLOAT4 objectColor;
};

Thanks!


texts:
Suppose my mana regeneration rate was calculated in this way:

ManaRegenRate = 0.01 × (BaseManaRegen + ManaRegenMultiplier × Willpower) × TotalMana

Where willpower is my attribute ranging from 0 to 100 and BaseManaRegen and ManaRegenMultiplier are some constants.

With this formula I would get mana regenerated per second.

How could I rearrange this formula to get the total amount of seconds to regenerate mana from 0 to full?


texts:
I'm trying to generate an asset bundle on a remote linux machine and stream the bundle to a running Unity instance.

Is it possible to download the same libraries Unity uses and compile on Linux?


texts: How can I resolve collisions at different speeds, depending on the direction?

texts:
I have, for all intents and purposes, a Triangle class that objects in my scene can collide with (In actuality, the right side of a parallelogram).

My collision detection and resolution code works fine for the purposes of preventing a gameobject from entering into the space of the Triangle, instead directing the movement along the edge.

The trouble is, the maximum speed along the x and y axis is not equivalent in my game, and moving along the Y axis (up or down) should take twice as long as an equivalent distance along the X axis (left or right).

Unfortunately, these speeds apply to the collision resolution too, and movement along the blue path above progresses twice as fast. What can I do in my collision resolution to make sure that the speedlimit for Y axis movement is obeyed in the latter case?

Collision Resolution for this case below (vecInput and velocity are the position and velocity vectors of the game object):

// y = mx+c
// solve for y. M = 2, x = input's x coord, c = rightYIntercept
lowY =  2*vecInput.x + parag.rightYIntercept ;

...

else
{
    // y = mx+c
    // vecInput.y = 2(x) + RightYIntercept
    // (vecInput.y - RightYIntercept) / 2 = x;

    //if velocity.Y (positive) greater than velocity.X (negative)
    //pushing from bottom, so push right.
    if(velocity.y > -1*velocity.x)
    {
            //change the input vector's x position to match the
            //y position on the shape's edge. Formula for line: Y = MX+C
            // M is 2, C is rightYIntercept, y is the input y, solve for X.
        vecInput = new Vector2((vecInput.y - parag.rightYIntercept)/2, vecInput.y);
        Debug.Log("adjusted rightwards");
    }
    else
    {
        vecInput = new Vector2( vecInput.x, lowY);
            Debug.Log("adjusted downwards");
    }
}


texts:
I am trying to detect collision between two triangles using Separating Axis Theorem however I am unaware what is wrong with my code. The CollisionHelper::isTriangleIntersectingTriangle is called every frame and passes in the vertices of both triangles. It never returns true, however. I've been stuck on this for days now. Any help is appreciated.
glm::vec3 CalcSurfaceNormal(glm::vec3 tri1, glm::vec3 tri2, glm::vec3 tri3)
{
    //Subtracts each coordinate respectively
    glm::vec3 u = tri2 - tri1;
    glm::vec3 v = tri3 - tri1;

    glm::vec3 nrmcross = glm::cross(u, v);
    nrmcross = glm::normalize(nrmcross);
    return nrmcross;
}

bool SATTriangleCheck(glm::vec3 axis, glm::vec3 tri1vert1, glm::vec3 tri1vert2, glm::vec3 tri1vert3, glm::vec3 tri2vert1, glm::vec3 tri2vert2, glm::vec3 tri2vert3)
{
    int t1v1 = glm::dot(axis, tri1vert1);
    int t1v2 = glm::dot(axis, tri1vert2);
    int t1v3 = glm::dot(axis, tri1vert3);
    int t2v1 = glm::dot(axis, tri2vert1);
    int t2v2 = glm::dot(axis, tri2vert2);
    int t2v3 = glm::dot(axis, tri2vert3);

    int t1min = glm::min(t1v1, glm::min(t1v2, t1v3));
    int t1max = glm::max(t1v1, glm::max(t1v2, t1v3));
    int t2min = glm::min(t2v1, glm::min(t2v2, t2v3));
    int t2max = glm::max(t2v1, glm::max(t2v2, t2v3));

    if ((t1min < t2max && t1min > t2min) || (t1max < t2max && t1max > t2min))
            return true;
    if ((t2min < t1max && t2min > t1min) || (t2max < t1max && t2max > t1min))
            return true;

    return false;
}

bool CollisionHelper::isTriangleIntersectingTriangle(glm::vec3 tri1, glm::vec3 tri2, glm::vec3 tri3, glm::vec3 otherTri1, glm::vec3 otherTri2, glm::vec3 otherTri3)
{
    //Triangle surface normals, 2 axes to test
    glm::vec3 tri1FaceNrml = CalcSurfaceNormal(tri1, tri2, tri3);
    glm::vec3 tri2FaceNrml = CalcSurfaceNormal(otherTri1, otherTri2, otherTri3);

    glm::vec3 tri1Edge1 = tri2 - tri1;
    glm::vec3 tri1Edge2 = tri3 - tri1;
    glm::vec3 tri1Edge3 = tri3 - tri2;
    glm::vec3 tri2Edge1 = otherTri2 - otherTri1;
    glm::vec3 tri2Edge2 = otherTri3 - otherTri1;
    glm::vec3 tri2Edge3 = otherTri3 - otherTri2;

    //axes
    //TODO: may need to (un)normalize the cross products
    glm::vec3 axis1 = tri1FaceNrml;
    glm::vec3 axis2 = tri2FaceNrml;
    glm::vec3 axis3 = glm::normalize(glm::cross(tri1Edge1, tri2Edge1));
    glm::vec3 axis4 = glm::normalize(glm::cross(tri1Edge1, tri2Edge2));
    glm::vec3 axis5 = glm::normalize(glm::cross(tri1Edge1, tri2Edge3));
    glm::vec3 axis6 = glm::normalize(glm::cross(tri1Edge2, tri2Edge1));
    glm::vec3 axis7 = glm::normalize(glm::cross(tri1Edge2, tri2Edge2));
    glm::vec3 axis8 = glm::normalize(glm::cross(tri1Edge2, tri2Edge3));
    glm::vec3 axis9 = glm::normalize(glm::cross(tri1Edge3, tri2Edge1));
    glm::vec3 axis10 = glm::normalize(glm::cross(tri1Edge3, tri2Edge2));
    glm::vec3 axis11 = glm::normalize(glm::cross(tri1Edge3, tri2Edge3));

    //Perform SAT
    if (SATTriangleCheck(axis1, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis2, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis3, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis4, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis5, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis6, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis7, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis8, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis9, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis10, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;
    if (SATTriangleCheck(axis11, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true;

    return false;
}


texts: What is the bare minimum I need to set up the Android SDK for Unity development?

texts:
I want to import my Unity project to Android, and I need to download the Android SDK, but I do not want to download any unnecessary components.

Do I need to download all platforms, or just the latest one? I am worried about the size of Android 7.1.1 (API Level 25); the SDK Manager reports this as the latest version, but I am not sure.

I only want to import my project for Android smartphones, with no plan of publishing it. I do not want to build to Android TV or Android Wear, for example. Do I need to download all of the contents under the specific platform? I ask because there are Android TV and Android Wear system images, and the files can get quite large.


texts: What's the best way to handle numerous recurring log entries in game loop?

texts:
I have a custom logging system, use of which is scattered all over the engine and game. The system is linked to a "LogStore" that has an std::vector<string> logs[NUM_LOG_TYPES] - each vector corresponds with it's log type (info, error, debug, etc.). There's one extra std::vector that has "coordinates" to all log entries in the order they were received.

Now, all the logging output is also displayed inside my development console in the game. The game console is handled by HTML-type GUI and therefore requires a new <p> element being added for each log output.

My problem is that the log entries that are generated in the main loop each frame freeze the engine, because they continue to add elements to the in-game console, and if the console or guy generates a warning - that creates an infinite logging loop.

I want to solve it by handling the recurring log entries in an elegant way that lets you know that something is critically wrong, but won't freeze the engine - like displaying the count of errors in the last 60 frames instead of displaying errors themselves. But how do you guys handle this? Does anyone know any nifty tricks to do this?

I understand the question may sound vague, but if someone came across this type of issue I'm sure they would know exactly what's happening.

Example problematic log entries:

OpenGL warnings (I actually do check for errors every frame in many
places)
Really any prints anywhere in the main loop (may be debugging, may
be warnings)


texts: Why does Unity think my RectTransform has changed?

texts:
I am working with UI.  I want to know when my RectTransform changes its position.  I am using transform.hasChanged:

void Update()
{
    if (transform.hasChanged)
    {
        Debug.Log("Updated Position");
        transform.hasChanged = false;
    }
}

However, it thinks it has always changed.  "Updated Position" is constantly printing out.  If I remove and then readd the component while in play mode, the issue resolves itself.  However, I don't want to have to do this, as it is very hacky.

I could just throw a bunch of if statements in there to check, but I'd prefer to make use of the build in transform.hasChanged property.

How can I check to see if my RectTransform has changed its position efficiently and elegantly?


texts:
Recently I am learning dot product,

While below code works from Unity's documentation,
http://docs.unity3d.com/ScriptReference/Vector3.Dot.html

 public Transform other;
    void Update() {
        if (other) {
            Vector3 forward = transform.TransformDirection(Vector3.forward);
            Vector3 toOther = other.position - transform.position;
         var dot = (Vector3.Dot(forward, toOther);
         Debug.Log(dot);

        }
    }

But it doesn't work when I change direction of "other".It keeps giving same value no matter how much I rotate other unlike when I rotate transform,it does change values.

For example,
transform is at 0 0 0 and other is at 0 0 10 both has 0 rotation so facing straight in Z axis.

The desiire out put I get is negative.

Now suppose I change rotation of transform to 180 then the output gets positive as expected.

I undo the rotation of trasnform and rotate other to 180 i.e., facing transform, then the output doesn't get change and show negative value only.Which is not correct as other is facing player..

Why is that the case? I am not able to get around it.


texts: issue with ray/physics collision detection

texts:
All,

I am trying to pick object using ray collision and bullet physics

I am initializing my projection and view matrix only once, here is the code

projectionMatrix = glm::perspective(90.0f, 4.0f / 3.0f, 0.1f, 100.0f);

float horizontalAngle = 3.14f;
float verticalAngle =0.0f;/// problems here

glm::vec3 direction(
    cos(verticalAngle) * sin(horizontalAngle),
    sin(verticalAngle),
    cos(verticalAngle) * cos(horizontalAngle)
);

glm::vec3 position = glm::vec3( 0.0, 10.0, 32.0 );

glm::vec3 right = glm::vec3(
    sin(horizontalAngle - 3.14f/2.0 ),
    0,
    cos(horizontalAngle - 3.14f/2.0 )
);

// Up vector
glm::vec3 up = glm::cross( right, direction );

viewMatrix =  glm::lookAt(
                            position,           // Camera is here
                            position+direction, // and looks here : at the same position, plus "direction"
                            up                  // Head is up (set to 0,-1,0 to look upside-down)
                       );

See below screenshot with actual object in the world

when I click on red area - it does not pick up object, but when i am click on green one - it does.

SMALL DETAIL:
I've used this tutorial http://www.opengl-tutorial.org/miscellaneous/clicking-on-objects/picking-with-a-physics-library. While I've applying constant change to view and projection matrix throug my mouse move and keys - detection work perfect, but once I've stooping doing it - it does not work.

Can someone help me out what I am doing wrong ?


texts:
I want to ask, is there way to load in xna all content from folder ?
For example in my content I have:
Images/hero
Images/car
Images/tree

I want to make something like this

Dictionary<string,Model> models = new ...

foreach(string name in content.getNames("Images"))
{
    models[name] = content.load<Model>("Images\\" + name);
}


texts: Transparent objects in the scene only get lit half way by point light

texts:
I have encountered a weird graphics problem, where all of our transparent objects in the scene only get lit half way (only from the y position downward) by a point light. This happens with all of our grass and tree shaders.
Also, when looking through translucent objects, they become really desaturated and gray-is which is an undesired effect.
Does anyone know how to deal with this problem? Please refer to the screenshots below.
I'm are using Unity 2020.1.14f, built-in render pipeline with a forward renderer.
For grass and trees we are using the Fantasy Adventure Environment, but all other grass shaders from other packages have the same problem.


texts:
I am making a card game where there are 21 cards on hand and 2 options from where user can draw cards to his hand and throw a card from hand.

I am new on game development and I'm following the principle of MVC.
Till now in my game I have a InputHandler class that handel the input. GameWorld and GameRender are two class which controll the game logic and render the game respectively. Both of these class are called by GameScreen class which extends Screen.

My question is how should I implement the touchListener to these cards. They are now just sprites and I have used texture Packer to create a spriteSheet

Doing research i have found that Stage and Actor are the things that I am looking for. Reading on wiki I found that these are useful to create menus. I've also read that working with stage and Actor is  complex for creating game environment and follow the rule of MVC.

So, please anyone could guide me a way from where should I need to move forward. This is the very basic move that I need to move but I know if I did wrong here, i have to pay much more later.


texts: Translation from one coordinate system to another having Z-offset issues

texts:
I'm using ARToolkit to do an augmented reality application, but my problem is really with the 3D coordinates.

In this application, I use my webcam to generate the scene.  I have two markers (printed - they have a thick black border with a letter inside to signify which object is to be drawn), and when the ARtoolkit framework recognizes the object, it will draw a specific OpenGL object on top of the marker in real time.

So onto the actual problem.

The first marker I consider to be my world coordinates, and the second to be a floating object that I will move around the scene.

The overall problem is that when I translate my secondary object to my world coordinate system, the Z-value is typically way off from what it should be, and I'm not sure how to rectify this (this is really my first foray into 3D programming).

As a note, I get the OpenGL 1x16 matrix in from the ARToolkit, using the recognized marker as (0,0,0).

First, I take the world coordinate system marker, store it into a 4x4 matrix, and then create a variable to hold its affine inverse (I am using a framework to do this part, so I don't think it is anything I'm doing here).

Next, I take the secondary marker and store that into a 4x4 matrix.

Finally, to move the secondary marker into the world coordinate system, I multiply them in-order, together, as such:

new_coords = world_coords_affine * secondary_coords

For my understanding, this should take the secondary object and move it to the world coordinates, so that I can simply draw it based on the new x, y and z values.

As I mentioned however, the Z coordinate is far greater than it should be.  I am drawing my scene typically at about (0, 0, 50) to hide the markers in the scene, and the secondary object tends to have Z-coordinates in the thousands when it is debugged.  For reference, I am actually putting the two markers directly next to each other, so really there should only be an X-offset (which I am seeing at least).


texts:
Is there any GuiLibrary available, which works with MonoGame? I know there are some GUI Libraries for XNA but I assume most will not work with MonoGame.

Even simple stuff like Buttons and Inputfields would help me...

Thanks.


texts: Approaching the Fun Factor in Game Design

texts:
As designers there has to be some ways you've approached establishing the 'fun-factor' in your games. You've likely done something in one game that may very well transfer into the future games you've worked on. You've likely played a game that did something really fun and you noticed that formula being applied to other games.

What are some ways to improve the fun-factor in game design? What makes Zynga games on Facebook so popular? Do rewards lead to more fun? Does failure lead to more fun? Does making a player come back in 2 hours lead to more fun? Have you read any good quotes or thoughts that really sticks in your mind?

There could be a good list of things to think about when approaching fun.


texts:
I'm looking to create a random vector within a cone given the radius (base).

It feels like I've been traversing through many pages on the internet and still I'm no further forward to getting an answer.

I was thinking I could get a point within the base of the cone and have it point towards the apex (then just use the inverse of that for my animation) but this seems like an incredibly long winded approach.


texts: How can I verify that a Steam key is legit?

texts:
I am developing a game that has online multiplayer. It will be available on Steam.

However, I do not want to use Steam authentication to use the online capabilities. I will use my own account system, so you must register with your email and password.

Which brings me to the next problem: how can I verify if this newly created account is a legit owner of the game in Steam? I can ask the player to provide their license key, but how could I verify that this key is valid? Does the Steam web API have a way to check if a key is valid, regardless of having been used to redeem the product or not?


texts: Stencil test doesn't work at all in Unity when I am using a custom shader

texts:
I am using Unity 2019.3 and I have a custom shader A which contains the code

Stencil{
     Ref 5
     Comp Equal
     Pass Keep
}

And the other custom shader B contains the code

Stencil{
     Ref 5
     Comp Always
     Pass Replace
}

The stencil test can do the right thing only if I add Fallback "Diffuse" in B, otherwise, it's never working. And A has no code related to Fallback.

Since shader A is using for post processing and I did something like

    buffer.SetGlobalTexture(ShaderID._MainTex,source);
    buffer.SetRenderTarget(destination);
    buffer.DrawMesh(mesh,Matrix4x4.identity,material,0,pass);

The material uses shader A.

Does this cause the issue because before today, I never use the Fallback during stencil test.

PS. You can use this and scene named SSS as example. In that scene the shader named Unlit/PBR has this issue. If you delete Fallback "Diffuse in that shader, the post processing effect never works.


texts:
I'm trying to find an elegant solution to calculating the x, y values of hexes that are crossed or intersected by a line or ray at a given angle from a given hex position on a hex grid. I do not want to use linear interpolation with an end point. I want a function that can calculate values to an arbitrary length with just the the angle. Pretend someone is standing at hex 4, 4 and shoots a bullet at angle 30. Which hexes will it cross? In the case of angle 30 where the angle is exactly between two hexes, default to the clockwise hex. I think there must be an elegant solution and at a certain point the number of "straight" moves vs. shifts "right" or "left" must form a repeating pattern. Furthermore, for a given angle, it will only shift right or left at some repeating interval, but never both. How do you calculate this? My grid uses x, y, (z) coordinates with "pointy top" hexes.

The function I'm trying to write would look like this: getXYOffsets(angle):Array of int;

The return value being a list of x, y offsets used to calculate the next hex's xy indefinitely (like I said, the offset pattern will repeat at some point).
For example, angle 0 will return an array of [1, 0] because a line shot that direction will move in the x direction infinitely and I just loop over that 2 value array to find my next x, y coordinates indefinitely.
For second example, angle 30 will return an array of [0, 1, 1, 0] because I would draw my line from 0, 0 -> 0, 1 -> 1, 1 -> 1, 2 -> 2, 2... indefinitely.
Obviously, less roundable angles will give longer returns arrays because you might have straight stretches that last a long time before finally "shifting". That's ok. I'll limit that after I get a solution to this math problem.

I just know this calculation is possible but my math is too weak to solve it. Any help would be SO appreciated!


texts: Using NinePatch in libGDX for Loading Bar

texts:
I am trying to create images for a loading bar in libGDX. I came across the NinePatch class and I was hoping to use it for this loading bar, since stretching images with a plain Texture or Sprite looks terrible. Does anyone have any examples on how to use this class? I have done some searching around and I've gotten it to work but the image I use just comes through as slightly transparent and gray. It just doesn't look like the same image. The actual loading bar itself seems to work fine as I just set the width of the foreground loading image. Here is the code I am using so far...

// Class vars
private NinePatch loadingBackground;
private NinePatch loadingForeground;

...

// In my constructor
loadingBackground = new NinePatch(new Texture(Gdx.files.internal("loadingback.png")), 8, 8, 8, 8);
loadingForeground = new NinePatch(new Texture(Gdx.files.internal("loadingfore.png")), 8, 8, 8, 8);

...

// Drawing
batch.begin();
loadingBackground.draw(batch, x, y, width, height);
loadingForeground.draw(batch, x, y, loadingWidth, height);
batch.end();

I am open to any other suggestions on how I should implement this as well.


texts: What models am I allowed use when selling my game?

texts:
I have purchased models through Daz3D, and I have downloaded a lot, for free. The 3D models were downloaded as .MMD or .FBX.

How do I tell if I can edit or use any of these models, in my game? When I sell my game, will I need a license to include these models?


texts: Unusual black squares in transparency effect after wake from sleep

texts:
I've encountered unusual black squares in semi transparent textures for a while now, usually in processes that were resumed after the computer woke from sleep. For example I've seen the effect in the Battle.net launcher by Blizzard frequently, on different machines.
But now I often encounter the effect in Unity in Play mode if I let the computer go to sleep. Restarting the scene fixes the display problem.

My 2 questions are:

What is that effect?
What do I need to do to prevent the effect from reaching my users?

In this screenshot there are 3 semi transparent particle effects on top of one semi transparent billboard, and at the bottom we see a part of an opaque sphere. The black squares seem to only affect a single one of the particle effects, and disappear if the effect is disabled, and reappear if it's re-enabled.

And here is the same effect in the Blizzard launcher:


texts: Why do games use tick rates in their networking and servers instead of an event system?

texts: Why do most games limit themselves with a tick rate in their networking? Isn't it better to make something like an even system where for example client A does something then the client sends related info to the server, and same for the server when something happens on it it sends a packet to the client, instead of using a tick rate and sending information only at some specific frequency. Is it cheaper/faster to send more data in a single packet or? And the same question goes for server tick rates, some servers limit themselves on specific tick rate frequencies, why do they do that? Why not just make a loop and run each tick after each other instead of having a gap between them or risking one tick to take longer than it should and causing bugs? What's the benefit of the tick rate approach for servers and for networking?


texts: Tile map only rendering 1 layer when it should be 3

texts:
I've been working on this for a while and I can not seem to figure it out. I had the fileParser() method in the constructor and it worked fine. Then I was told it's very bad practice to have it in the constructor. So I moved it to it's own method(which required making most of the variables static) and moved the call to the main Game class and now it runs without errors, but only my last layer is rendering. I've moved things in the class around. I've used more variables than there are at the moment. I've checked my files and they are for sure 32 by 32. So I have no clue why this is happening.

import com.stardust.main.gfx.Assets;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TileMap
{
   private static final int TILE_SIZE = 32;
   //placeholder for each tile
   BufferedImage[] tiles = new BufferedImage[37];

   //array of tile types
   private static int[][] map = new int[TILE_SIZE][TILE_SIZE];
   //position coordinates
   private int posX, posY;
   //Edge of map Cooridinates
   public static int sx, sy;
   private String fileName;
   private static int x = 0, y = 0;

   public TileMap(int posX, int posY, String fileName) throws IOException
   {
       this.fileName = fileName;
       this.posX = posX;
       this.posY = posY;
       this.sx = map.length * TILE_SIZE;
       this.sy = map.length * TILE_SIZE;

       setTile();

   }

   public void render(Graphics g)
   {
       for(int x = 0; x < TILE_SIZE; x++)
       {
           for(int y = 0; y < TILE_SIZE; y++)
           {
               int textureType = map[x][y];
               BufferedImage texture = tiles[textureType];
               g.drawImage(texture, posX, posY, null);
               posY += TILE_SIZE;
           }
           posX += 32;
           posY = Game.mapY;
       }
       posX = Game.mapX;
       posY = Game.mapY;

   }

   private void setTile()
   {
       tiles[0] = Assets.grass;
       tiles[1] = Assets.dirt;
       tiles[2] = Assets.water;
       tiles[3] = Assets.tree;
       tiles[4] = Assets.multiTree;
       tiles[5] = Assets.NSpath;
       tiles[6] = Assets.uprtPath;
       tiles[7] = Assets.EWpath;
       tiles[8] = Assets.upltPath;
       tiles[9] = Assets.dnltPath;
       tiles[10] = Assets.dnrtPath;
       tiles[11] = Assets.watgrsdn;
       tiles[12] = Assets.watgrslt;
       tiles[13] = Assets.watgrsup;
       tiles[14] = Assets.watgrsrt;
       tiles[15] = Assets.watgrsSE;
       tiles[16] = Assets.watgrsSW;
       tiles[17] = Assets.watgrsNW;
       tiles[18] = Assets.watgrsNE;
       tiles[19] = Assets.wallWood;
       tiles[20] = Assets.pointer;
       tiles[21] = Assets.pathOpRt;
       tiles[22] = Assets.pathOpLt;
       tiles[23] = Assets.pathOpDn;
       tiles[24] = Assets.pathOpUp;
       tiles[25] = Assets.pathOpAll;
       tiles[26] = Assets.roughWood;
       tiles[27] = Assets.pathOpen;
       tiles[28] = Assets.counter;
       tiles[29] = Assets.storeDude;
       tiles[30] = Assets.pot;
       tiles[31] = Assets.singleHouse;
       tiles[32] = Assets.doubleHouse;
       tiles[33] = Assets.wepBanner;
       tiles[34] = Assets.armBanner;
       tiles[35] = Assets.innBanner;
       tiles[36] = Assets.blankTile;
   }

   public void fileParser() throws IOException
   {
       BufferedReader in = new BufferedReader(new FileReader(fileName));

       String line;

       while((line = in.readLine()) != null)
       {
           String[] values = line.split(",");

           for(String str : values)
           {
               int str_int = Integer.parseInt(str);
               map[x][y] = str_int;
               ++y;
           }
           ++x;
           y = 0;
       }
       x = 0;

       in.close();
   }
}


texts: What is the proper way to convert meters to pixels when using Box2D?

texts:
I'm working on a platformer and I've chosen to use Box2D for physics but I'm having trouble converting meters to pixels. I have a static object and a dynamic object. The dynamic object falls onto the static object but when the dynamic object hits the static object, they don't touch, they're about a meter apart when they're supposed to be touching.

As you can see from the screenshot, the dynamic object (rat) is hovering above the static object (blue rectangle) when they're supposed to be touching. I assumed it was a problem with my meters-to-pixels code so I fiddled with it and inspected variables in the debugger and still can't figure out what I'm doing wrong.

Rendering is done in pixels (via SDL2) and the origin is in the top-left corner of the window. +x is right and +y is down.

Physics is done in meters (via Box2D) and the origin is in the bottom-right corner of the window. +x is right and +y is up.

Heres the code to create the dynamic object.

b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.fixedRotation = true;

b2Body *body = world.CreateBody(&bodyDef);

b2PolygonShape shape;
shape.SetAsBox(1.0f, 1.0f);

b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 10.0f;

body->CreateFixture(&fixtureDef);
body->SetTransform({0.0f, 10.0f}, 0.0f);

And here's the code to create the static body

b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;

b2Body *body = world.CreateBody(&bodyDef);

b2PolygonShape shape;
shape.SetAsBox(WINDOW_METER_SIZE.x, 2.0f);

b2FixtureDef fixture;
fixture.shape = &shape;
fixture.friction = 0.0f;

body->CreateFixture(&fixture);
body->SetTransform({0.0f, 0.0f}, 0.0f);

The Rect and RectPx classes represent a rectangle as a top-left point p and a size s.

To get the Rect of the b2Body used for drawing.

b2Body *body;
const Rect rect = {body->GetPosition(), {1.0f, 1.0f}};

Heres the code to transform a rectangle in meters to a rectangle in pixels

RectPx transform(const Rect rect) {
  return {
    {
      rect.p.x * PIXELS_PER_METER,
      (-rect.p.y + WINDOW_METER_SIZE.y - rect.s.y) * PIXELS_PER_METER
    },
    rect.s * PIXELS_PER_METER
  };
}

I later use the RectPx to call SDL_RenderFillRect and SDL_RenderCopy which both expect a rectangle in the described format.

I really hope there's an obvious mistake in my code somewhere that a Box2D guru can spot.

Thank you in advance for reading this very long question.


texts: Is there anything equivalent to Portal 2's linked_portal_door in any other engines?

texts: I need the functionality of the linked_portal_door that's in Portal 2. I've searched a little in UDK and mostly got people trying to duplicate the portal gun. Does anyone know if UDK, CryEngine, Unity3D, or any other engine has something similar? I'm not against using Source, I just want to know what my options are.


texts: Why would OpenGL ignore GL_DEPTH_TEST setting?

texts:
I cannot figure out why some of my objects are being rendered on top of each other. I have Depth testing on.

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

Do I need to draw by order of what is closest to the camera? (I thought OpenGL did that for you.)

Setup code:

 private  void setUpStates() {
    glShadeModel(GL_SMOOTH);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightModel(GL_LIGHT_MODEL_AMBIENT, BufferTools.asFlippedFloatBuffer(new float[]{0, 0f, 0f, 1f}));
    glLight(GL_LIGHT0, GL_CONSTANT_ATTENUATION,BufferTools.asFlippedFloatBuffer(new float[]{1, 1, 1, 1}) );

    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT, GL_DIFFUSE);
    glMaterialf(GL_FRONT, GL_SHININESS, 50f);
    camera.applyOptimalStates();

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    glEnable(GL_TEXTURE_2D);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);

    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}

Render Code:

private void render() {

    // Clear the pixels on the screen and clear the contents of the depth buffer (3D contents of the scene)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Reset any translations the camera made last frame update
    glLoadIdentity();
    // Apply the camera position and orientation to the scene
    camera.applyTranslations();
    glLight(GL_LIGHT0, GL_POSITION, BufferTools.asFlippedFloatBuffer(500f, 100f, 500f, 1));
    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    for(ChunkBatch cb : InterthreadHolder.getInstance().getBatches()){
        cb.draw(camera.x(), camera.y(), camera.z());
    }

}

The draw method in ChunkBatch:

    public void draw(float x, float y, float z) {
    shader.bind();
    shader.setUniform("cameraPosition", x,y,z);
   for(ChunkVBO c : VBOs){
        glBindBuffer(GL_ARRAY_BUFFER, c.vertexid);
        glVertexPointer(3, GL_FLOAT, 0, 0L);
        glBindBuffer(GL_ARRAY_BUFFER, c.colorid);
        glColorPointer(3, GL_FLOAT, 0, 0L);
        glBindBuffer(GL_ARRAY_BUFFER, c.normalid);
        glNormalPointer(GL_FLOAT, 0, 0L);
        glDrawArrays(GL_QUADS, 0, c.visibleFaces * 6);
    }
    ShaderProgram.unbind();
}


texts:
The object have forwardForce.
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce=800f;
    void Start()
    {

    }

    void FixedUpdate()
    {
        rb.AddForce(0,0,forwardForce * Time.deltaTime);
        if(Input.GetKey("d")){
            rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }else if(Input.GetKey("a")){
            rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }
    }
}

Now, the issue is I want to stop that object while falling down(not on that ground anymore).The camera will keep running but, I just want to stop that object. Which means if the is not on ground anymore than velocity=0


texts:
cube
 [[ 1.  0.  0. 6.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

view
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]

final
[[ 1.  0.  0. 6.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

Hello! I have a cube and I'm trying to move it around. The above are the calculated matricies for the cube, viewport, and the combined matrix after multiplication. The result is this:

I'm not sure why it's being warped like this instead of scooting over a bit. Any idea?


texts: OnTriggerEnter not working when placed inside Update()

texts:
I'm making a scanner that scans the "world" (like a 10 x 10 space), and I'm trying to sense a GameObject called pointer.
They both have colliders, they both have triggers, and the scanner has a rigidbody. I have tried the OnTriggerEnter method outside of the update, and it worked, but as soon as I put it inside of Update, it breaks.
I don't have to worry about being specific on what the scanner is detecting, because those two are the only ones with a collider.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scan : MonoBehaviour
{
    public int worldHeight;
    public int worldWidth;

    public bool sensed;

    public bool spaceBar = false;

    void Update()
    {
        if (Input.GetKeyDown("space") && spaceBar == false)
        {
            spaceBar = true;

            sensed = false;

            //brings scanner to top left corner of world
            transform.position = new Vector3(worldWidth / 2 * -0.64f + 0.32f, worldHeight / 2 * 0.64f + 0.32f, -1);

            for (int sizey = 0; sizey < worldHeight; sizey++)
            {
                if (sensed == false)
                {
                    //shifts scanner down
                    transform.position = new Vector3(worldWidth / 2 * -0.64f - 0.32f, transform.position.y, -1);
                    transform.position = transform.position - new Vector3(0, 0.64f);

                    for (int sizex = 0; sizex < worldWidth; sizex++)
                    {
                        if (sensed == false)
                        {
                            //shifts scanner right
                            transform.position = transform.position + new Vector3(0.64f, 0);

                            void OnCollisionEnter2D(Collision2D grid)
                            {
                                //not working ;-;
                                sensed = true;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            spaceBar = false;
        }
    }
}


texts: Display loading screen after scene change but wait for coroutine to finish

texts:
I thought I'd understood how coroutines work but I'm still experiencing problems getting them to run when I want them to run:

There are two scenes in my game: The main menu one and a game one.
The main menu consists of a couple of buttons that let you choose a txt file and if you click on one of them, the "game" scene is loaded (SceneManager.LoadScene("Game");), which first thing reads the chosen txt file from HDD. Afterwards there's some other stuff that has to be finished (FinishRest()) but it's pretty quick anyway.

I want to display a loading screen while it's reading the file (no need to update it), which can take a while. Clicking on the button freezes the game in the main menu while the txt file is being read and it never displays the loading screen. That's why I put the actual reading part inside a coroutine and start it as soon as the "game" scene is loaded:

//In SciptA (derives from MonoBehaviour, is on the main camera)
void Awake() {
    loadingOperationReadTxt = StartCoroutine(ClassB.ReadTxtCoroutine());
    FinishRest();
}

//In ClassB (derives from ScriptableObject)
public IEnumerator ReadTxtCoroutine() {
    loadingPanel.SetActive(true);
    loadingPanel.GetComponentInChildren<Text>().text = "Reading txt file...";
    output = ClassC.ReadTXT(); //ClassC derives from nothing
    loadingPanel.SetActive(false);
    yield return null;
}

The problem is that it never displays the loading screen like this (I'm guessing because I don't let it tick until after I'm already done), so I tried to fix it by putting another yield return null; right before output = ClassC.ReadTXT();. Now it does display the loading screen but skips the rest of the coroutine and goes right to FinishRest(), which fails, of course, because it's missing the data from the txt file.

I want to display a loading screen but I also have to wait for the coroutine to finish before actually calling FinishRest() (I miss Tasks...). How can I accomplish this?


texts:
I want to revive an old MMO.

Only the old client exists from the game, so I would have to write a whole server for it.

I'm not sure how to start editing things in the already made client. Most likely I will need catch requests and somehow change those to my own.

How do I go about actually working/editing that client? What should I use, having only .dlls on some other already compiled files?


texts:
I create a simple 2D Unity ( C#) animation, which is a tutorial for me.

I have a PLAYER.

1) My player moves with the mouse (he follows mouse).

2) After colliding with a square, he destroys it.

I don't have a problem with it, everything works ok.

However, I would like the player to destroy the squares in the right order(in right sequence): 1-2-3-4.

If he destroys them in the wrong order(wrong sequence) , for example 1-3 (first collid with number 1 and then number 3), animation end.

I know how to end animations when I touch an wrong thing, but I do not know how to make it in the right order (specific sequence).

How to make a player have to destroy squares in a specific order?

PS. Sorry for my English. If someone doesn't understand something, I'll try to write it simpler :)

Until now, with the help of tutorials, I did something like that:

 // this script is on the empty game object; just one of these, and it keeps track of which game object is the right one to be destroyed next.
int index = 0;

[SerializeField]
GameObject [] gamePieces;

public void GotDestroyed(GameObject go) {
   if(gamePieces[index] == go) {
      // correct one was destroyed.
      ++index; // if index >= gamePieces.Length, it's game over.. all done.

  }
    else {
       // if we're here, the one destroyed was not the next in the list
    }
 }

But how to further transform this code to solve the problem?


texts:
I am just getting started with Unity and I'd like to ask a question. If I have a "Vehicle" object that has two children: "FrontWheel" and "BackWheel" (both 'wheels' are cylinders), how should I set everything up such that I can move the entire vehicle by turning its wheels?

When I apply a torque to "FrontWheel", the vehicle starts to move, but instead of the whole thing the moving together, the chassis is rolling on the cylinders and eventually falls off.

How can I prevent it from doing that?


texts: Playing one song after another results in horrible grinding noise; how can I fix this?

texts:
I'm currently working on a game using slick2d java framework and I want to set it up so that the intro to a piece of music will play once, then the main body of the piece loops infinitely. I've got:

public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
    BossInt = new Music("OST/bossintronly.wav");
    Boss1 = new Music("OST/bossloop.wav");
    Boss1.setVolume(0.5f);
    BossInt.setVolume(0.5f);

    BossInt.play();
}

then in my update method

if (BossInt.playing() == false) {
        Boss1.loop();
}

It ends up playing through the intro once as intended, but then instead of looping the main body as I'd hoped it just blasts a horrible grinding noise. It's definitely not a problem with the wav file, I've checked and replaced that multiple times.

Can anyone help me out?


texts:
I am working on a fabric simulator at low level, I have done some work and at this point there are some points where I would appreciate help.

The input of the program is a DRF file. This is a format used in sewing machines to indicate the needles where to move.

The 2D representation is accurate, I parse the DRF info to a polyline, apply tensions and I extrude this in a openGL render.

Now I am trying to achieve the 3D ZAxis physics. I tried two methods:

1) Asuming information

First method is based on constrains about the process of  manufacturing:
we only take care of the knots where a set of yarns interact and comupte z separation in this crucial points. The result is regular: good in a lot of cases but with a lot of botched jobs in order to avoid causistincs where this is not a good assumtion (for example, doing beziers, collisions in zones between this crucial points). We desist on this alternative when we saw there was a lot os causistic we would have to hardcode,probably  creating aditional gliche.

2) Custom 2D Engine

The second attempt is to aprox the yarns with box colliders 2D, check collisions with a grid, and compute new Z in funcion of this. This is by far more expensive, but leads to a better results. Although, there is some problems:

The accuracy of box colliders over the yarn is not absolute ( there are ways to solve this but it would be great to read some alternatives)
There is not iterative process:

First we compute collisions pairwise, and add to each collider a list of colliding colliders. Then, we arrange this list and separate the Z axis in function of yarn's radius with center 0.The last step is to smooth the results from discrete z to a beziers or smoothing filters. This leads to another glitches.
If I extend this recomputation to all the collisions of the current collisions, I get weird results because z changes are bad propagated( maybe I am not doing good this point)
Some colliders are recomputed wrong ( first computed yarns have more posibilites to be altered for the last ones, leading on gliches)

some of the glicthes (mainly in the first yarns computed:

Details of bad aproximated curves:

At this point I have some questions:

Can I fix this glitches (or a great part at least)?
Glitches about bad aproximation and glitches for z recomputation
A 3D engine like ODE could do the job in a reasonable time?

If you need some specific code don't hestiate on ask for it.

Thanks a lot!


texts: What is the difference between a library and an engine?

texts:
I am working on a library to help 2D game development with Scala. So far, it is a collection of helpful classes, file loading, collision detection, images, sprites, etc.

So when does it stop being a class library and start being an engine? Where exactly lies the difference between useful framework and a game engine?


texts: How does a server receive every player input with a server-authoritative structure?

texts:
I've been having a lot of trouble understanding networking in fast-paced games. A server has a fixed tickrate, and the server receives input from clients at a fixed rate as well. Let's assume that a client is running at 300fps but is sending 64 updates to the server a second.
Clearly, the client did not send data about every frame, which means that certain inputs were not sent to the server. However, in every networked first-person shooter, the server still seems to pick up every input.

In this image, a client presses W at a certain frame, but that frame's data is not sent to the server.
A possible solution would be to send the server updates equal to framerate. But if a client is playing at a high framerate, they could be sending too much data for the server to handle.
So how does a server receive every input from clients?


texts:
I've created a small simulation game and I have a basic neural network in place, each "creature" in my game has random weights on it's nodes and they all behave differently.

Their goal is to stay inside a circular "safe zone" that moves around the center of the game world. After 1000 generations of evolution not a single one of them makes any attempt to follow the circle around, so I was thinking I either..

Don't know how to train them properly
Don't know how to find who should live/ die.
Using the wrong input/ outputs.

Here is the diagram of the brain (ignore the numbers)

Can anyone shed any light on what my issue is here? I'm sorry if this is vague I've only been using these for a couple of hours. But to elaborate on my question, what kind of inputs/ outputs should I be using with my neural network and what is the general procedure (in respect to my evolution approach) to train them to do the correct thing?? Could the error be caused by the number of nodes in the hidden layer or something?


texts: Tiled deferred shading without compute shader

texts:
I'm building a deferred renderer and since I want to support a large amount of lights in the scene I've had a look at tiled deferred shading.

The problem is that I have to target OpenGL 3.3 hardware and it doesn't support GLSL compute shaders.

Is there a possibility to implement tiled deferred shading with normal shaders?


texts: Does Google Play allow an account to log in to the same game on 2 devices?

texts:
I'm developing an online Android game with Unity. I want all Google Play accounts to have only one session logged in at a time.

Do I need to write my own code to disconnect an existing session on new login attempts, or does Google Play already handle this?

Edit:

An idea popped to my mind. I can save the logged in device's state to a a file on Google's Saved Games cloud, and write an instance-specific identifier to that file that indicates who has logged on last. And checking file constantly on all instances will allow me to disconnect instances whose identifier doesn't match the one on the file on the cloud.

Do you think this is a good idea? I mean, fetching file from cloud every second or so?


texts:
I have this problem to solve using Cocos2d-x 3.x:
In my game there is water represented by rectangle texture, modified by the code on the go. I also have a character moving around, rotating etc.

I would like to achieve silhouette effect when he goes into the water - so if pixel of character texture is not transparent and pixel of water texture is not transparent, color should be changed lets say to gray. I would like it to work as fragment shader added to character sprite.

The problem is that I have no idea how to go from character UV coords to water texture coords (positions, rotations and dimensions of textures are different). I am also not sure the approach proposed by me is the correct one, maybe there is better way to do it?

Could you please give me some thought how it should be done? Any code is welcome too!

Edit: here is a visualization, red triangle is character, it changes color as it submerges


texts: How can I make a health bar — a UI element — part of a character prefab?

texts:
Description
I want my character prefabs to come with their own health bar, but I can't simply add one as part of the prefab, because it's a UI element and therefore goes into a Canvas.
Potential Solution
I could write a script that takes in a separate health bar prefab and instantiates it when the character prefab's instantiated, but it's one extra script.
Is there a more conventional way to do this? I'd think this is a common problem.


texts: How do I simplify terrain with tunnels or overhangs?

texts:
I'm attempting to store vertex data in a quadtree with C++, such that far-away vertices can be combined to simplify the object and speed up rendering.

This works well with a reasonably flat mesh, but what about terrain with overhangs or tunnels? How should I represent such a mesh in a quadtree?

After the initial generation, each mesh is roughly 130,000 polygons and about 300 of these meshes are lined up to create the surface of a planetary body. A fully generated planet is upwards of 10,000,000 polygons before applying any culling to the individual meshes. Therefore, this second optimization is vital for the project.

The rest of my confusion focuses around my inexperience with vertex data: How do I properly loop through the vertex data to group them into specific quads? How do I conclude from vertex data what a quad's maximum size should be? How many quads should the quadtree include?


texts: Play animation of the jump properly in Unity2D

texts:
Here is what I want to do:

when player jumps I would like to play an animation of jumping once
on playing it I would like to stop at the penultimate animation frame till the player falls to the ground
on falling to the ground I would like to play the last frame of the animation

Here is a screenshot which I hope will make my objective clearer:

Here is an idea I have right now:

I will add an event to occur exactly between penultimate and last animation frames, this even will stop animation.
When grounding I will add an event which will continue my animation to play till the end.
At the end I will use a flag to say all other animations that they are free to play.

Here is stuff which I think is a flaw:

using of flags will make any code messier in general
there will be problems if a user jumps once and try to run, jump again or do something that needs an animation right away after grounding because the last frame will be playing at that time
I do not know how to stop animation, since according to this stopping an animation also Rewinds it to the Start, while I do not want to rewind it to start, but stop before the last animation frame.


texts: I'm making a casual game on iOS platform. But I'm not sure Do the consumers like my game. How can I make a market test for my game?


texts: Severe color banding while applying SSAO

texts:
I'm trying to implement SSAO together with deferred shading. The deferred shading works just fine, and so does calculating the AO as seen in the first image below. However, taking AO into consideration when combining the light with gbuffer data produces color banding as seen in the second figure.

The third image shows a result after messing around, ending up multiplying the final color by 3, increasing the overall light intensity. The light banding is somewhat alleviated, and further increasing the light intensity reduces banding even more. This is of course not a solution but perhaps a step in the right direction.

Nevertheless it got me thinking. For the resulting texture I'm using an RGBA8_UNORM format, which gives me 256 distinct values for the various channels, right? I store the AO in a single 8 bit channel texture. The only light affecting the mesh is ambient light, and the color of the mesh is a single shade of green. Doesn't this mean that the already low bits of the render target have to store even more shades when AO is applied? This makes sense considering that increasing the precision of the AO map doesn't fix the problem, but not so much when simply increasing the intensity of the final color reduces the banding. How is this generally handled when using deferred shading? I should note that attenuating the final color with the normalized horizontal pixel value in [0,1] produces similar banding, which is perfectly vertical instead.

Can it be something that has to do with gamma correction (I don't explicitly do it myself)? Is that something one must do when using deferred shading?

Edit:

It turned out that DXUT made the back buffer SRGB (meaning that it handles gamma correction), but gamma was never corrected at the beginning, resulting in incorrect gamma handling. Correcting gamma while sampling textures resulted in clearer, but darker colors. Increasing ambient light to compensate for the darkness resulted in less banding while still having dimmer surroundings. Another bonus is that the colors don't look as washed-out as before.

It's not completely perfect however, but maybe HDR rendering can take care of that (big maybe, I don't much about it at all). Also, colors of the mesh are constant, which probably contributes. I believe having high-frequency textures makes the little banding that's left less apparent.


texts: How to implement specific custom events in an Event Condition Action (ECA) game system?

texts:
A while ago I implemented a simple event-condition-action system for my game trying to emulate the Warcaft 3 trigger system (in a small scale, of course):

So far, it works fine, but there is something I have not been able to implement yet. It is the specific events or conditioned events (I don't know if there is a proper name for them). Following the example of the picture, a set of actions are performed if that event is triggered and matches the condition specified PLUS another condition within the event.

Every time I have worked with event systems, events (understanding them as event types) are non-mutable strings, ints, enums or any type of unique ids that allow subscription/mapping/etc. so someone else is notified. The way the system of the picture works clashes with what I know, as the event type can be "edited". What I mean is that, from my point of view, it seems there are two type of events in the example: "A unit dies" and "A unit owned by player 12 dies". But I'm almost sure it's not how it works.

Do systems like this one keep the same "constant event structure" as I conceive it and have an inner condition layer checking for that specific event? Do they work in a completely different way that I'm unaware? How, then?


texts: How do I get the distance between 2 points on an isometric grid? I'm creating a facebook isometric game (in as3), and when I move around a particular type of building, I need to know if it comes within range of another type of structure, for example a tree. I tried taking the grid x,y points for both items, and calculating the x,y from that but it doesn't seem to work.


texts: Translate extrinsic rotations to intrinsic rotations ( Euler angles )

texts:
The problem I have is very frustrating:
I am using the Jitter Physics library which gives Quaternion rotations, you can extract the extrinsic rotations but I need intrinsic rotations to rotate in OpenTK (There are other reasons as well so I don't want to make OpenTK use a Matrix)

GL.Rotate(xr, 1, 0, 0)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(zr, 0, 0, 1)

EDIT : Response to the first answer

Like This?

GL.Rotate(zr, 0, 0, 1)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(xr, 1, 0, 0)

Or This?

GL.Rotate(xr, 1, 0, 0)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(zr, 0, 0, 1)

GL.Rotate(zr, 0, 0, 1)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(xr, 1, 0, 0)

GL.Rotate(xr, 1, 0, 0)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(zr, 0, 0, 1)

I'm confused, please give an example


texts:
This may be obvious and trivial for you but as I am a newbie in programming I come with a specific question.

I have three loops in my game engine which are input-loop, update-loop and render-loop. Update-loop is set to 10 ticks per second with a fixed timestep, render-loop is capped at around 60 fps and the input-loop runs as fast as possible. I am using one of the Javascript frameworks which provide such things but it doesn't really matter.

Let's say I am rendering a tile map and the view of which elements are rendered depends on camera-like movement variables which are modified during key pressing. This is only about camera/viewport and rendering, no game physics involved here.

And now, how can I handle input events among these loops to keep consistent engine reaction? Am I supposed to read the current variable modified with input and do some needed calculations in a update-loop and share the result so it could be interpolated in a render-loop? Or read the input effect directly inside the render-loop and put needed calculations inside?

I thought interpreting user input inside an update-loop with a low tick rate would be inaccurate and kind of unresponsive while rendering with interpolation in the final view. How it is done properly in games overall?


texts: How to rotate an object to face another in Unity?

texts:
I'm having an issue where I can't seem to rotate my bullet appropriately whenever I spawn one. I currently have a capsule prefab I am testing with. I spawn it with the following code.

        GameObject b = (GameObject)Instantiate(Resources.Load<GameObject>("Prefabs/Bullet"));

I am using the following code to try and orient the bullet so that it lays along the imaginary ray between it's spawn location and the centre of the target.

    void Start() {
    go = InputController.instance.hit.transform.gameObject;
    transform.position = new Vector3(transform.parent.position.x, transform.parent.position.y - 5, transform.parent.position.z);
}

void Update () {
    transform.LookAt(go.transform.position);
    Vector3 rotation = transform.eulerAngles; //THIS IS THE LINE I NEED TO ALTER
    transform.rotation = Quaternion.Euler(rotation);
    transform.position = Vector3.MoveTowards(transform.position, go.transform.position, SPEED * Time.deltaTime);
    Debug.DrawRay(transform.position, transform.forward * 10000000, Color.red); //DEBUGGING
    Debug.DrawRay(transform.position, transform.up * 1000000, Color.green); //DEBUGGING
}

Essentially the issue I am having is how I can calculate the rotation of the object based on the two I have available.

As you can see the line that I can't seem to calculate is the second line of the Update method, what it needs to do is orient the Vector3.up direction of the object to run along the Vector3 created by linking its position with the target location.

Interestingly the bullet is already laying horizontally but the LookAt method changes its rotation so I just need to fix it but I'm not sure on the math to do that.


texts:
I'm using the IntersectMovingAABBAABB implementation from the book Realtime Collision Detection and I'm having a little bit of an issue. When I have two AABBs next to each other (not touching), A being stationnary and B moving up or down, I'm getting a result saying there's a collision. Obviously this is wrong.

 _______     _______
|       |   |       |
|   A   |   |   B   |  B moving up/down
|_______|   |_______|

I've rechecked my code multiple times to make sure I had the same thing as in the book. Stepping through the code, I realized that the check for v[i] < 0 and v[i] > 0 will never be true for either X or Z axis when moving straight up or down. Therefor, no checks for intersections on these axis will be done. I find that quite weird, and I was wondering if I was missing something, or if this code is simply bad.

Here's my implementation for reference:

public static bool IntersectMovingAABBAABB(AABB a, AABB b, Vector3 va, Vector3 vb, out float first, out float last, out BlockFace face)
{
    face = BlockFace.None;
    if (TestAABB(a, b))
    {
        first = last = 0;
        return true;
    }

    Vector3 v = vb - va;
    float current;

    first = 0;
    last = 1;

    for (int i = 0; i < 3; i++)
    {
        if (v[i] < 0)
        {
            if (b.Max[i] < a.Min[i]) return false;
            if (a.Max[i] < b.Min[i]) if ((first = Math.Max(current= (a.Max[i] - b.Min[i]) / v[i], first)) == current) face = (BlockFace)(1 << (i));
            if (b.Max[i] > a.Min[i]) last = Math.Min((a.Min[i] - b.Max[i]) / v[i], last);
        }

        if (v[i] > 0)
        {
            if (a.Max[i] < b.Min[i]) return false;
            if (b.Max[i] < a.Min[i]) if ((first = Math.Max(current = (a.Min[i] - b.Max[i]) / v[i], first)) == current) face = (BlockFace)(1 << (i + 3));
            if (a.Max[i] > b.Min[i]) last = Math.Min((a.Max[i] - b.Min[i]) / v[i], last);
        }

        if (first > last) return false;
    }

    return true;
}


texts: Jitter Physics not working correctly. Going through objects and getting pushed back when touching walls

texts:
I am trying to use the Jitter physics engine, however, I can't get it to work correctly. For example, when I touch the side of a cube, it pushes me far back in the opposite direction. While I am flying back, if I hold the opposite directional key, I keep getting slower until I come to full stop.

Other times, I go right through the floor. I followed this tutorial.

I gave my floors BoxShapes and a RigidBody. I set them to static so the rigidbodies won't move. I did the same in my Player class but didn't set it to static.

How do I make it work correctly? If someone knows a better tutorial or physics engine I can use in C# with MonoGame/XNA, please let me know.


texts: Relation between game systems and components in a component-based architecture?

texts:
Based on a question I previously asked here regarding to decoupling input from other components of an entity I developed a small component architecture on top of XNA to understand how everything works and plays together. Basically, my architecture has the following components/services/systems:

Game

This is the root of any game, responsible for ticking the game loop (updating, drawing) as well as instantiating all systems.

GameModule

A game module responsible for a certain aspect of the game, such as UI (UIModule), input (InputModule), animations (SpriteAnimationModule), scenes (SceneStackModule) etc.

Scenes

Holds the current state of the game. Basically an entity manager. :)

Entity

Entity which only holds a collection of components and very basic world space information such as position, rotation etc.

Component

A component of an entity, which can be anything (SpriteComponent, ScriptComponent, ControllerComponent)...

However now I seem to have a problem of the responsibilities between my game systems (modules) and the components, which are not aware of each other. For instance, I have an UIModule instantiated in my game, which I need to update/render before any other systems in order to appropriately handle input events on the UI. For this, I'd need to loop through all UIComponents - which are unfortunately encapsulated within the current scene. Which in turn is only accessible via the SceneStackModule (LIFO collection for scenes). So I have to either make my UIModule aware of the concept of scenes (by making the SceneStackModule a dependency of the UIModule), create an UIModule for each scene or make the UIModule a dependency and register the UIComponent twice (once in the entity, once in the module).

Approach 1

public class UIModule : GraphicalModuleBase {
    public UIModule(SceneStackModule sceneStack) { }

    public void Draw(GameTime gameTime) {
        var uiComponents = SelectUIComponentsFromEntities();
        uiComponents.Draw(gameTime);
    }
}

Approach 2

public class MainScene : Scene {

    public UIModule UIModule { get; } = new UIModule();

    public void Draw(GameTime gameTime) {
        var uiComponents = SelectUIComponentsFromEntities();
        uiModule.Draw(gameTime, uiComponents);
    }
}

Approach 3

public class UIComponent : ComponentBase {
    public UIComponent(UIModule uiModule) {
        uiModule.RegisterComponent(this);
    }
}

All three approaches are not very nice (why does the UI need to be aware of scenes, why no components need modules as dependencies or why do I have to declare my 'main render logic' (UI before everything else) a part of every scene?). So I either clearly missed something here or that's another nasty part of game development. :/


texts:
I can't quite figure this out, no matter the various modifications I make.

What should happen: I want this to only move the player on left click/left up if i have previously right clicked

What actually happens: Regardless of which mouse button I click/unclick, it activates the direction function.

The offending code:

class Controller_Mouse : public Component
{
public:

    Component_Transform *transform;

    void init() override
    {
        transform = &entity->get_component<Component_Transform>();
    }

    void update() override
    {
        if (Game::event.type == SDL_MOUSEBUTTONDOWN)
        {
            if (SDL_BUTTON_RIGHT)
            {
                transform->active = true;
            }

            if (SDL_BUTTON_LEFT)
            {
                if (transform->active == true)
                {
                    std::cout << "transform vals: " << transform->position.x << ", " << transform->position.y << std::endl;
                    std::cout << "click vals:     " << Game::event.motion.x << ", " << Game::event.motion.y << std::endl;

                    transform->target.x = Game::event.motion.x; transform->target.y = Game::event.motion.y;
                }

                transform->active = false;
            }
        }
        if (Game::event.type == SDL_MOUSEBUTTONUP && SDL_BUTTON_LEFT)
        {
            transform->direction(transform->position.x, transform->position.y, transform->target.x, transform->target.y);
        }
    }
};


texts: Import Blender model into Unity with Textures

texts: I tried a very straightforward import of the Monk model from https://opengameart.org/content/monk into Unity 5.6.1f1, and ended up with no color/texture on the model. Why?


texts:
Me and my (new) company want to sell a very simple game, but we want it so that only the person that buys it can play it.

I want to know if it's possible to make a "registration" window pop up when the game either first starts or when it is being installed (still haven't decided whether or not to use an installer or not). It would require the person to input a registration key and it would then check that key against a database to 1. check to see if it's actually there and 2. to see if it has not been used already. If both are true, it lets you install or play the game an infinite number of times on that computer up until it is uninstalled.

Is this possible in the c#/xna code, or would i have to use some advanced form of executable programming?


texts: Copying a texture's colors to a new texture to create a new sprite

texts:
Let mySprite be some .PNG sprite:

Texture2D tex = mySprite.texture;
Sprite sprite = Sprite.Create(tex, new Rect(0,0,tex.width,tex.height),new Vector2(0.0f,0.0f),1.0f);

The resulting sprite can be used by a SpriteRenderer just fine. Now, let's do something a bit more redundant:

Texture2D tex = mySprite.texture;
Texture2D tex2 = new Texture2D(tex.width,tex.height);
Color[] colors = tex.GetPixels(0,0,tex.width,tex.height);
tex2.SetPixels(colors);
Sprite sprite = Sprite.Create(tex2, new Rect(0,0,tex.width,tex.height),new Vector2(0.0f,0.0f),1.0f);

All I am doing is create a new texture, copy the original texture's colors, and then used this new texture to create my sprite. However, when I use this sprite with a SpriteRenderer, all I get is a grayish rectangle.

What is wrong with this code?


texts:
First off, I'm not referring to scene management; I'm defining game state loosely as any sort of state in a game which has implications about whether or not user input should be enabled, or if certain actors should be temporarily disabled, etc.

As a concrete example, let's say it's a game of the classic Battlechess.  After I make a move to take another player's piece, a short battle sequence plays.  During this sequence, the player shouldn't be allowed to move pieces.  So how would you track this sort of state transition?  A finite state machine?  A simple boolean check?  It seems the latter would only work well for a game with very few state changes of this sort.

I can think of a lot of straightforward ways of handling this using finite state machines, but I can also see them quickly getting out of hand.  I'm just curious if there's a more elegant way to keep track of game states/transitions.


texts: How do I get information about the level to the player object?

texts:
I have a design problem with my Player and Level class in my game.

So below is a picture of the game. The problem is I don't want to move on the black space and only the white space. I know how to do this as all I need to do is get the check for the sf::Color::Black and I have methods to do this in the Level class. The problem is this piece of code

   void Game::input()
{
    player.input();
}

void Game::update()
{
    (*level).update();
    player.update();
}

void Game::render()
{
    (*level).render();
    player.render();
}

So as you there is a problem in that how do I get the map information from the Level class to the Player class.

Now I was thinking if I made the Player position static and pass it into the Level as parameter in update I could do it. The problem is interaction. I don't know what to do. I could maybe make player go into the Level class. However, what if I want multiple levels?

So I have big design problems that I'm trying to solve.


texts: [Unity] Render an animated texture to a screen

texts:
I'm looking for a way to write a typed text on a texture, and then render it on a screen: in the game it's just the screen of a computer where a scientist is typing text on.

The texture will be already generated: it will have several textures in it.

I can't find any obvious way to do a simple render to texture with unity, how could I do that ?


texts: How To Deselect (Unfocus) All gameObjects in a Unity Scene View?

texts:
When I'm done with moving and rotating gameObjects in a Unity scene, I want to deselect everything to not accidentally change it. How?

In some applications ESC key does the trick, in others 'D' (deselect) comes to rescue. But I don't know any remedy in Unity. My workaround is that I click somewhere in the Project View (I don't like this approach because it brings up the inspector for that asset).


texts: OpenGL glVertexAttribFormat vs glVertexAttribPointer

texts:
I am attempting to change my code from using glVertexAttribPointer to glVertexAttribFormat as I have heard it;s more efficiend since it reduces binding calls overhead.

I have 2 versions of the code, one working one not.

The code looks like:

glGenBuffers(1, &tvbo1);
glBindBuffer(GL_ARRAY_BUFFER, tvbo1);
glObjectLabel(GL_BUFFER, tvbo1, 21, "\"Mesh Vertex Buffer\"");
glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*triangle.size(), triangle.data(), GL_STATIC_DRAW);

glGenBuffers(1, &tvbo2);
glBindBuffer(GL_ARRAY_BUFFER, tvbo2);
glObjectLabel(GL_BUFFER, tvbo2, 22, "\"Mesh Normals Buffer\"");
glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*ns.size(), ns.data(), GL_STATIC_DRAW);

glEnableVertexAttribArray(0);
//glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, 0); //comment
glVertexAttribBinding(0,0); //comment

glEnableVertexAttribArray(1);
//glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribFormat(1, 3, GL_FLOAT, GL_FALSE, 0); //comment
glVertexAttribBinding(1,1); //comment

GLuint ptrs[] = {tvbo1, tvbo2};
GLintptr offsets[] = {0,0};
int strides[] = {0,0};
glBindVertexBuffers(0, 2, ptrs, offsets, strides); //comment

So whenever you see a //comment. That's to denote that in the other version that line is commented out.

The version that does work uses:

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

The version that does not work uses:

glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, 0); //comment
glVertexAttribBinding(0,0); //comment

glBindVertexBuffers(0, 2, ptrs, offsets, strides); //comment

The difference between working and not working is having a purple triangle vs having a black screen.

It seems that the error comes from the line

glBindVertexBuffers(0, 2, ptrs, offsets, strides); //comment

As having that line present results in a black screen regardless of the rest of the code.


texts:
I'm developing a 2D physics platformer game, with commercial purposes. Almost everything is finished:

An original game concept
The whole 2D self-written game engine
A level interpreter to read xml levels
A level editor with an advanced GUI to generate levels in xml
An advanced level object system
Profile manager (load & save game progress)
etc ...

But, my problems are of course inspiration for levels...

Is it possible to publish my game concept and ask community for level designs? And still keep my game concept save from being copied by others. Do I have copyrights on a game concept for a game which isn't officially released?

And if I should ask community, should I do an action like, for everyone who submits an approved level design (not the xml, but only a sketch), they receive one cent per sold copy of the game?

What do you think? Tips, pitfalls?

Thank you in advance!

For the interested people, here is a screenshot from the level-editor:

Fullscreen image