texts: GLSL - multiplying fragment output color by normal after calling texture function displays wrong texture

texts:
So I'm quite new to OpenGL/GLSL. I'm trying to make multitexturing and simple normal lighting work.
Here is a Vertex shader:

#version 130

uniform mat4 transform;

in vec3 vertPos;
in vec2 texUV;
in vec3 vertNorm;
in uint thisLayer;

out vec2 fragTexCoord;
out vec3 fragNorm;
out float fragLayer;

void main()
{
    gl_Position = transform * vec4(vertPos, 1.0f);

    fragTexCoord = texUV;
    fragLayer = float(thisLayer);
    fragNorm = vertNorm;
}

... and here is Fragment shader:

#version 130

uniform sampler2DArray texArray;
uniform uint texCount;
uniform float rTime;

in vec2 fragTexCoord;
in vec3 fragNorm;
in float fragLayer;

out vec4 color;

void main()
{
    float actual_layer = max(0, min(texCount - uint(1), floor(fragLayer + 0.5))); // Getting texture layer
    vec3 texCoord = vec3(fragTexCoord, actual_layer);

    color = texture(texArray, texCoord);
}

And it works fine:

Multiplying color.rbg by any constant works as expected:

color = texture(texArray, texCoord);
color.rgb *= vec3(0.5, 0.5, 0.5);

But if I try to multiply color.rgb by a normal, like this:

vec3 finalNorm = (normalize(fragNorm) + vec3(1,1,1))/vec3(2,2,2);
color = texture(texArray, texCoord);
color.rgb *= finalNorm;

The wall texture changes to the last texture in the array (the one on the top):

I have no idea why this happens. I normalize vertex normals and map their values into [0, 1] range, so colors will stay in [0, 1] range after multiplication as well. It is supposed to simply shift the colors intensity, like it did while multiplying by a constant, not change the texture itself, right?
I am aware of the fact that this is not how you perform normal lighting, however, this is not the correct behavior as well, and I'm ripping my hair off as to why.
Any help is appreciated. I will provide more info if needed.

EDIT:
OS is Windows 10. GPU's: Intel HD 4600/Nvidia GTX 860M (happens on both of them). OpenGL version 4.3.0 build 20.19.15.4624.

Some additional info:

I use SOIL library to load data from PNG files. I use:

glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, img_width, img_height, layer_count * 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

to create a container for texture array, and use:

glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, img_width, img_height, layer_count, GL_RGBA, GL_UNSIGNED_BYTE, data);

to load data into it. One issue I have with this is that glTexImage3D takes layer_count (the number of textures) multiplied by 2, and I have no idea why as well! Maybe this is somehow related to the issue I'm having above?


texts: I get GL_INVALID_VALUE after calling glTexSubImage2D

texts:
I am trying to figure out why my texture allocation does not work.  Here is the code:

glTexStorage2D(GL_TEXTURE_2D, 2, GL_RGBA8, 2048, 2048);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2048, 2048, GL_RGB,
                GL_UNSIGNED_SHORT_5_6_5_REV, &BitMap[0]);

glTexSubImage2D returns GL_INVALID_VALUE but the maximum texture allowed is 16384x16384 on my card.

The source of the image is 16bit (Red 5, Green 6, Blue 5).


texts:
I'm trying to show the players name on the GUI with a label.

GUI.Label(new Rect(10,10, 100, 30), playerName);

Instead of use the default style I want to use a different font with larger character.

Any suggestion to achieve this?


texts:
I am developping a spaceinvader-like game. There comes the problem of how to handle collision detection.

At first I was doing like that :

forEach(fireBall : fireBalls) {
    forEach(stormTrooper : stormTroopers) {
        if (collides(fireBall, stormTrooper)) {
             // Explode

But then when playing I had the feeling the game was slowing down at some point, and I tought it had something to do with the multiple elements and the double loop.

So I tried to break the loops whenever I had the chance, changing the forEach loops to for loops at the same time :

for (var i = 0; i < fireBalls.length; i++) {
     if (stormTroopers.length > 0 && fireBalls[i].y > stormTroopers[0].y) {
          break;
     }
     for (var j = 0; j < stormTroopers.length; j++) {
         if (fireBalls[i].y > (stormTroopers[j].y + 31)) {
             break;
         }

If the fireball isn't on the same "y" as any stormtrooper, the fireballs following are not going to be either, so no need to check. Same for the stormtroopers loop.
This works only if the list is ordered, meaning the first stormTrooper of the list has the highest "y" value.

The problem in my game is that all stormTroopers don't have the same speed, so I need to sort the list each time.

This leads to my question : in order to enhance the performance, I tried to break the loops, but for that I had to add a new operation : sort the list of the stormTrooper. Is it worth it?


texts:
In the generic mario style game you collect coins as you go along your primary adventure (i.e. get to other side of the map). They usually offer generic additions like the ability to get extra lives and +score. Other games like platformers use them additionally as currency for skins etc. Donkey kong 64 its bananas and they do something similar, only sometimes its linked to progression itself (banana medals). These all relate to collecting the same kind of item where touching them is all you need to do.
Are there any examples or ideas applying the concept of coins (things you collect in a gameworld as you go along) to a more interesting game mechanic? For example in shooters I suppose it would be collecting weapons. In my case I'm specifically interested in what might be added to a top-down 2d game. Whether they should be optional asides (mario coins) or more important to progression (banana-medals unlocking maps)...I would look for alternatives more to the optional side.
Looking more to the collection side of the mechanic. There's alot you could do with the money, but don't focus so much on that part.


texts:
Let's say we have 100 objects of each of few types, that may have an effect if they collide with one other type, or they may not.

Is it better to have quadtrees for each object type, and check collisions directly between the object types we want; or is it better to have a single quadtree holding all objects, then generate collision pairs and check if the collision has effect or not?

Is having a single quadtree slower?
Why not having multiple quadtrees, one for each object type?


texts: Checking if object passed between two other objects

texts:
I have a three objects (strikers), lets say red, green and blue.

When I apply force to the green object I want to check if it has passed between red and blue or not. See the image below for an illustration.

Is there any line collider or something for that?


texts: ImGui, how to get value that the mouse is pointing at in a VSliderFloat widget

texts:
I am using ImGui::VSliderFloat to create a vertical slider in the GUI of my application. To do this I just copied the imgui demo code (imgui_demo.cpp), which reads something like

ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, "");
                if (ImGui::IsItemActive() || ImGui::IsItemHovered())
                    ImGui::SetTooltip("%.3f", values[i]);

In the demo they have stored some values in the array values[7]. My question is about the tooltip. When you point your mouse at the VSlider, the tooltip you get is the current value in values[i]. Is there some way I that I could ask ImGui for the value of the slider that the mouse is pointing at?


texts:
I'm currently working on a clone of an old turn-based strategy game "Stars!" and am looking for solutions to a challenge in game engine implementation.

The premise

The premise of the game is that every player takes control over the entire race of his denizens (called "colonists") and fight other players to conquer the known part of the galaxy.
Each player can design their race as they please. The first choices presented when creating a race are those of the Primary Racial Trait (PRT - must select exactly one from a list of 10) and Lesser Racial Traits (LRT - can select any number of them from a list of 14). A PRT usually modifies several aspects of the base game, e.g. sets starting technology level, gives some starting spaceships, controls the availability of certain ship parts and modifies the rules of the game for that player while LRTs provide minor advantages/disadvantages.

A few examples to show the extent of game modifications as well as interactions between them:

PRTs can modify the same part of the rules from two directions: Inner Strength PRT - 10% increased strength of defending colonists; War Monger PRT - 10% increased strength of attacking colonists.
PRT and LRT can directly modify the same "property" of a race: Jack Of All Trades PRT - +20% maximum planet population; Only Basic Remote Mining LRT - +10% maximum planet population; they cumulate multiplicatively (+32%).
LRTs can work conditionally based on other LRTs: Improved Fuel Efficiency grants access to several unique types of engine, where one of them is granted only if another LRT No Ram-Scoop Engines is not chosen.
PRT can fundamentally modify the game mechanics: Alternate Reality PRT races do not live on planets but rather in orbiting starbases. Rules of economy (resource production) are completely different for them as they do not build planetary facilities (factories and mines).

Constraints - the challenge

Make it possible to design new PRTs and LRTs and put them in the game without much pain.
(Induced from previous) They must be in some way decoupled from the main engine (so the core "rules engine" cannot be based on if/switch statements that change flow based on PRT/LRT).

The question

What design patterns would be suitable to this problem of "pluggable modifiers"?

The language is C#, if that helps with suggesting more specific solutions. So far my brain is wandering in the realm of attaching the Traits to events in the engine where it calculates certain properties (so they could modify the output of these calculations), but I don't want to suggest too much.


texts: What would it take to program a game engine like the build engine

texts:
My favorite games of all time are thanks to Ken Silverman's BUILD engine, The engine that brought us DukeNukem 3D, Shadow warrior and Blood. I've read a few articles on the build engine however I haven't found any good ones that go in depth. Ive been programming in C for 3 and a bit years now and am reading through many books every day, so I believe I have minimal skills needed to take on this task.

I was wondering what it would take to make my own "Build engine". What sort of mathematics do I need to learn/know, What books would you recommend, what sort of programming do I need to know (I.E low level programming with bitwise operators or any thing else). My current goal is not to make a game like Duke nukem 3D but to merely make a engine that supports things like sloped walls, translucency, wall and floor sprites etc.


texts: How do I make one ui slider control all of the game audio?

texts: I use the ui slider to control how loud is the game, what I want to know is how to make one ui slider control all of the game audio?


texts: Determine the startposition for Perlin worms

texts:
I want to implement Perlin worms for the level generation of my 2D game and I was wondering, which options exist to find the startposition for the worms.

My idea was to randomly start zero to X (constant) worms per chunk and use random x and y coordinates for each worm. Are there other options I could try and compare to my idea?


texts:
I don't have a dedicated GPU on my laptop and would like to know which settings to change in order to get semi decent performance. I don't care if the 3D camera will render everything pixelated.

At this moment when I try and run the First person shooter demo it will run around 40fps and when shooting the gum the  frame rate drops to around 25fps.

I think my CPU is pretty descent for an laptop. Its an i7-3667U & I have 16gb ram. Intel HD Graphics 4000. Also I already have unreal installed on my SSD.

My goal is development only and I will use low poly models when possible.


texts: Using multiple indexes with buffer objects in OpenTK

texts:
I've got multiple buffers in OpenGL holding data on position, normals and texcoords.

I also have an equal number of buffers holding distinct index data for each of those buffers.

I quite like this format (indvidual indexes for each buffer) utilised by COLLADA since it strikes me as optimally efficient at accessing each buffer.

I've set up pointers to the relevant data arrays using VertexPointer, NormalPointer, etc however I have no way to assign pointers to the index buffers since DrawElements appear to only look at one ElementArrayBuffer.

Can I utilise multiple indices some way or will I be better off using a different technique which can support this? I'd prefer to keep the distinct indices if at all possible.


texts:
I'm trying to make an ai so the paddles will move to position before the ball reaches it. I'm not sure how to go about it in this case.
Here's the game http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds

// Function to increase speed after every 5 points
function increaseSpd() {
    if(points % 4 == 0) {
        if(Math.abs(ball.vx) < 15) {
            ball.vx += (ball.vx < 0) ? -1 : 1;
            ball.vy += (ball.vy < 0) ? -2 : 2;
        }
    }
}

// Track the position of mouse cursor
function trackPosition(e) {
    mouse.x = e.pageX;
    mouse.y = e.pageY;
}

// Function to update positions, score and everything.
// Basically, the main game logic is defined here
function update() {

    // Update scores
    updateScore();

    // Move the paddles on mouse move
    if(mouse.x && mouse.y) {
        for(var i = 1; i < paddles.length; i++) {
            p = paddles[i];
            p.x = mouse.x - p.w/2;
        }
    }

    // Move the ball
    ball.x += ball.vx;
    ball.y += ball.vy;

    // Collision with paddles
    p1 = paddles[1];
    p2 = paddles[2];

    // If the ball strikes with paddles,
    // invert the y-velocity vector of ball,
    // increment the points, play the collision sound,
    // save collision's position so that sparks can be
    // emitted from that position, set the flag variable,
    // and change the multiplier
    if(collides(ball, p1)) {
        collideAction(ball, p1);
    }

    else if(collides(ball, p2)) {
        collideAction(ball, p2);
    }

    else {
        // Collide with walls, If the ball hits the top/bottom,
        // walls, run gameOver() function
        if(ball.y + ball.r > H) {
            ball.y = H - ball.r;
            gameOver();
        }

        else if(ball.y < 0) {
            ball.y = ball.r;
            gameOver();
        }

        // If ball strikes the vertical walls, invert the
        // x-velocity vector of ball
        if(ball.x + ball.r > W) {
            ball.vx = -ball.vx;
            ball.x = W - ball.r;
        }

        else if(ball.x -ball.r < 0) {
            ball.vx = -ball.vx;
            ball.x = ball.r;
        }
    }

    // If flag is set, push the particles
    if(flag == 1) {
        for(var k = 0; k < particlesCount; k++) {
            particles.push(new createParticles(particlePos.x, particlePos.y, multiplier));
        }
    }

    // Emit particles/sparks
    emitParticles();

    // reset flag
    flag = 0;
}

//Function to check collision between ball and one of
//the paddles
function collides(b, p) {
    if(b.x + ball.r >= p.x && b.x - ball.r <=p.x + p.w) {
        if(b.y >= (p.y - p.h) && p.y > 0){
            paddleHit = 1;
            return true;
        }

        else if(b.y <= p.h && p.y == 0) {
            paddleHit = 2;
            return true;
        }

        else return false;
    }
}

//Do this when collides == true
function collideAction(ball, p) {
    ball.vy = -ball.vy;

    if(paddleHit == 1) {
        ball.y = p.y - p.h;
        particlePos.y = ball.y + ball.r;
        multiplier = -1;
    }

    else if(paddleHit == 2) {
        ball.y = p.h + ball.r;
        particlePos.y = ball.y - ball.r;
        multiplier = 1;
    }

    points++;
    increaseSpd();

    if(collision) {
        if(points > 0)
            collision.pause();

        collision.currentTime = 0;
        collision.play();
    }

    particlePos.x = ball.x;
    flag = 1;
}

// Function for emitting particles
function emitParticles() {
    for(var j = 0; j < particles.length; j++) {
        par = particles[j];

        ctx.beginPath();
        ctx.fillStyle = "white";
        if (par.radius > 0) {
            ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false);
        }
        ctx.fill();

        par.x += par.vx;
        par.y += par.vy;

        // Reduce radius so that the particles die after a few seconds
        par.radius = Math.max(par.radius - 0.05, 0.0);

    }
}


texts: How to instantiate a prefab at mouse location in the editor in unity?

texts:
I want to instantiate a prefab at the mouse position in the editor. All the answers I found till now are for instatiate a prefab at runtime but i want to instantiate in the editor.
Currently I am trying to use input.GetMouseButtonDown but that doesn't seem to work ?
Also is it fine to use raycasting in the editor itself?
EDIT: Alright I found that we need to use eventtype.MouseDown
but now the script is not executing?
there are no errors in the console window
using UnityEngine;
using UnityEditor;
[ExecuteInEditMode]
public class mapMaker : Editor
{
    public GameObject rock;
    private void OnSceneGUI()
    {
        if (Event.current.type == EventType.MouseDown)
        {
            Ray ray = Camera.current.ScreenPointToRay(Event.current.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 1000.0f))
            {
                Debug.Log(Event.current.mousePosition);
                Vector3 newTilePosition = hit.point;
                Instantiate(rock, newTilePosition, Quaternion.identity);
            }
        }
    }
}

```


texts:
I have created a dialog in Libgdx main menu screen.

I have tried

dialog.setPosition(300, 300);
dialog.show(stage);

It doesn't do anything. Is it a camera trick? Am I missing something?


texts: OpenGL Outlining Cubes in a Greedy Meshed Mesh

texts:
So I've managed to get myself a greedy meshing algorithm implemented for a little voxel game I'm developing to teach myself LWJGL/OpenGL, and it's going great. The thing is, I don't plan on using textures (to truly fit into the voxel theme), and I was wondering how I could go about outlining each individual voxel (there can be multiple per quad). Here's the code I've come up with so far in my fragment shader:

float epsilon = 0.025f;
float xx = fract(mvVertexPos.x);
float yy = fract(mvVertexPos.y);
float zz = fract(mvVertexPos.z);
bool nearX = (xx >= -epsilon && xx <= epsilon);
bool nearY = (yy >= -epsilon && yy <= epsilon);
bool nearZ = (zz >= -epsilon && zz <= epsilon);
if ((nearX && !nearY && !nearZ) || (!nearX && nearY && !nearZ) || (!nearX && !nearY && nearZ)) {
    fragColor -= vec4(0.3, 0.3, 0.3, 0.0);
}

In this sample, mvVertexPos is the position of the vertex from the vertex shader transformed by the model matrix:

vec4 mvPos = modelMatrix * vec4(vert, 1.0);
mvVertexPos = mvPos.xyz;

This method, however, leads to a mesh that looks like this:

When it looks like this without that part of the shader:

And I am trying to make it looks similar to less (not black, but darkened around the edges, just pretend I outlined all the voxels, that's laziness on my part):

I have also ensured that it's not me just duplicated meshes and overlapping them in the world, so that weirdness is a result of my lack of shader experience.

The chunks of terrain will always have the edges of the cubic voxels fall on whole numbers (negative and positive). Essentially, this would be a shader that darkens the frag colors near whole numbers in the world.

Thanks in advance for your help :)

Update: It would appear that the problems stem from the fract calls in these lines:

float xx = fract(vertWorldPos.x);
float yy = fract(vertWorldPos.y);
float zz = fract(vertWorldPos.z);

Drawing the colors like this: fragColor = vec4(xx, yy, zz, 1.0); yields this unexpected behavior:

Note: I also changed the fract(mvVertexPos.-) calls to fract(vertWorldPos.-) because mvVertexPos has been transformed by the matrix, while vertWorldPos has not.


texts:
I'm working with a game in C# XNA and I want to draw a texture and a position in the middle of the screen.
The thing is that I want the viewport to move around and not the player.
So for example:
If I push right I want the viewport to move right and keep the player in the middle of the screen.

Since GraphicsDevice.Viewport.X and Y are not variables, I have no idea how to do this.


texts: How should I implement a first-person camera?

texts:
I'm a beginner programmer and I'm creating a project which allows me to walk around rooms via a first person camera. So far, I have the buildings drawn and  on, but now I'm stuck and don't know how to make a first-person camera to allow me to walk around.

Could anyone point me towards a camera class I could use, or some useful code?


texts: Call touchUp() programattically for sprite in LibGDX

texts:
I'm trying to call touchUp() for a sprite i've created in my app.

i'm getting success but the co-ordinates do not match while i call it manually.

final int x = (int)mySprite.getX() + 10;
final int y = (int)(Gdx.graphics.getHeight() - (mySprite.getY() - 5));

touchDown(x, y, 0, 0);

this code calls method perfectly but positions do not match. x and y values that i get in touchUp() method is different. it call touch up event of another sprite.


texts: How to impale and stack targets correctly according to the collider and its coordinate?

texts:
I'm making another simple game, a catch game, where a spawning target game object must be captured using a skewer to impale it. Here how:

At the start, the falling object (in red) will fall in a vertical direction (in blue)

When aimed properly, the target will fall down along the line of the skewer. (in blue) Then, another target is spawned and will fall vertically. (in red)

When aimed successfully again in a streak, the second target will fall along the skewer and stacked. Same process over and over when another target is spawned.

However, when I test run it on the scene tab in Unity, when impaled several targets, instead of a smooth flow and stacking it ended up overlaying it instead of stacking it up like a pancake. Here's what it look like:

As I noticed when reaching the half-way of my progress, I tried to figure out how to deal with collider bodies without sticking each other so that it will actually stack like in the example of the image at no. 3. Here's the script code I added in the target game object:

using UnityEngine;
using System.Collections;

public class ImpaleStateTest : MonoBehaviour {

    public GameObject target;
    public GameObject skewer;

    public bool drag = false;

    private float stack;
    private float impaleCount;

    void Start () {
        stack = 0;
        impaleCount = 0;
    }

    void Update () {
        if(drag) {
            target.transform.position = new Vector3 (DragTest.dir.transform.position.x, DragTest.dir.transform.position.y - 0.35f, 0);
            target.transform.rotation = DragTest.degrees;
            target.rigidbody2D.fixedAngle = true;
            target.rigidbody2D.isKinematic = true;
            target.rigidbody2D.gravityScale = 0;

            if(Input.GetMouseButton(0)) {
                Debug.Log ("Skewer: " + DragTest.dir.transform.position.x);
                Debug.Log ("Target: " + target.transform.position.x);
            }
        }
    }

    void OnTriggerEnter2D(Collider2D collider) {
        impaleCount++;
        Debug.Log ("Impaled " + impaleCount + " time(s)!");
        drag = true;
        audio.Play ();
    }

}

Aside from that, I'm not sure if it's right but, the only way to stick the impaled targets while dragging the skewer left or right is to get the X coordinates from the skewer only. Is there something else to recommend it in order to improve this behavior as realistic as possible? Please help.


texts:
Within a static library I'm creating, I have a struct called Vertex that holds three variables used for an image drawn on a plane:

struct Vertex
{
    glm::vec2 Position;
    glm::vec3 Color;
    glm::vec2 TexCoord;
};

and a list of vertices like so (outside of the class):

const std::vector<graphics::Vertex> vertices =
        {
            { { -0.5f, -0.5f },{ 1.0f, 0.0f, 0.0f },{ 0.0f, 0.0f } },
            { { 0.5f, -0.5f },{ 0.0f, 1.0f, 0.0f },{ 1.0f, 0.0f } },
            { { 0.5f, 0.5f },{ 0.0f, 0.0f, 1.0f },{ 1.0f, 1.0f } },
            { { -0.5f, 0.5f },{ 1.0f, 1.0f, 1.0f },{ 0.0f, 1.0f } }
        };

When I run the program, I get a thrown exception and points to line 637 in xmemory0:

template<class _Objty,
class... _Types>
void construct(_Objty *_Ptr, _Types&&... _Args)
{   // construct _Objty(_Types...) at _Ptr
    ::new ((void *)_Ptr) _Objty(_STD forward<_Types>(_Args)...); // here
}

But when I put all my code in main.cpp without modifying anything, the program works as expected.

When the thrown exception is triggered from running my code in the static library, the output points to (in red) Position, Color and TexCoords with these values:

Position x=0.0... y=4.059...e-34
Color x=7.119e-43#DEN y=4.0428...e-34 z=7.119e+34
TexCoord x 1.40...e+34 y=4.591e-41#DEN


texts:
Your game expects a certain asset to be loaded, but it isn't found. How should the situation be handled? For example:

Texture* grassTexture = LoadTexture("Grass.png"); // returns NULL; texture not found
Mesh* car             = LoadMesh("Car.obj");      // returns NULL; 3D mesh not found

It might have been accidentally deleted by the user, corrupted or misspelled while in development.

Some potential responses:

Assertions (ideally only during development)
Exit the game gracefully
Throw an exception and try to handle it.

Which way is best?


texts: Adding Animation to Object—Unexpected Behavior

texts:
I've been following the Unity 2D roguelike tutorial and I'm a bit confused about something. When he drags a series of sprites to his player object, a dialog box appears that prompts him to name and choose a location for his animation. I have seen this behavior in a couple video tutorials now.

When I do this, it simply creates the animation and animation controller in the sprite folder and nothing more. This becomes a bit tedious after a while and I'm not sure these animations are being associated with the object correctly.

What am I doing wrong?


texts: Detect transform from detection of QR code?

texts:
I want to calculate the transform I need to render a 3D object in my world.

How I see my idea:

You open a camera
You point it at a QR code
The app detects the QR code and returns the 4 corners and the correct direction
The app calculates the transform that this QR code is currently at (I need help with this step)
The app uses that transform to render the 3D object in a fixed position over the QR code

I want something like Vuforia, but for QR codes (as they are used often).

I don't really know how I can extract the transform from the detected QR code (I will get the location of the 4 corners)


texts: Bilinear filtering by sampling corners of a texel

texts:
I'm trying to do bilinear filtering in texels to get the convoluted value of a 3x3 block. Implemented as below:

offsetx = 1/width
offsety = 1/height

Fragment shader:

"varying vec2 vTextureCoord;\n" +
"uniform samplerExternalOES sTexture;\n" +
" vec2 scale = vec2(offsetx,offsety);\n" +
" vec4 p00 = texture2D(sTexture, vTextureCoord + 0.5*scale*vec2(-1,-1));\n" +
" vec4 p02 = texture2D(sTexture, vTextureCoord + 0.5*scale*vec2(1,-1));\n" +
" vec4 p20 = texture2D(sTexture, vTextureCoord + 0.5*scale*vec2(-1,1));\n" +
" vec4 p22 = texture2D(sTexture, vTextureCoord + 0.5*scale*vec2(1,1));\n" +
" vec4 pconvolve = 0.25*(p00 + p02 + p20 + p22);\n" +

Vertex shader:

private final String mVertexShader =
            "uniform mat4 uMVPMatrix;\n" +
            "uniform mat4 uSTMatrix;\n" +
            "attribute vec4 aPosition;\n" +
            "attribute vec4 aTextureCoord;\n" +
            "varying vec2 vTextureCoord;\n" +
            "void main() {\n" +
            "  gl_Position = uMVPMatrix * aPosition;\n" +
            "  vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
            "}\n";

where Matrices are unity matrices and position and texture cordinates are :

private final float[] mTriangleVerticesData = {
            // X, Y, Z, U, V
            -1.0f, -1.0f, 0, 0.f, 0.f,
            1.0f, -1.0f, 0, 1.f, 0.f,
            -1.0f,  1.0f, 0, 0.f, 1.f,
            1.0f,  1.0f, 0, 1.f, 1.f,
    };

Texture filtering:

GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);

Issue:

I have an original implementation where I calculate a convoluted value of a 3x3 block using a Gaussian-Blur algorithm that uses GL_NEAREST as texture mapping.
For optimization, I thought of replacing the 3x3 Gaussian Blur with sampling on 4 corners of the texel (as that is also having same weightage). Here I used GL_LINEAR.

The expectation was that the results I get from these 2 approaches should not vary by a wide range. But I got a huge difference. Visually both looks almost the same.

I tried changing the first texture mapping to GL_LINEAR and compared. That also resulted in a difference. (A difference in R, G and B component values between 2 approaches up to 5 was acceptable.) I got about 45 in some cases.

Testing methodology:

For the same frame, I used glreadPixels and compared the RGB value for all pixels in both cases. Most of them were same, but some showed huge difference:

Gaussian        9BD6DA

Bilinear        8BC0C3


texts: Interactive Controls (switches, knobs, buttons) in Unity

texts:
I'm working on a puzzle aspect of a game, and wanted to make a section where players relay information to one another, and have to input the correct values.

At its most basic, its a few stored variables that exist only for this, and really don't do anything. i.e. "Turn on shields" would just be a bool. "Set phasers to 5" an int. etc.

I'm trying to figure out the best way for a player to interact with these variables. I've considered GUI elements placed on gameobjects, but I'm not entirely comfortable with Unity's GUI system.

Should i take the time and use the GUI system, or would setting up my own scripts to edit the controls (toggle boxes, sliders, knobs) be a more simple solution?

Thanks in advance!


texts:
I want to create shaders but I need a tool to create and see the visual result before I put them into my game. As to determine if there is something wrong with my game or if it's something with the shader I created. I've looked at some like Render Monkey and OpenGL Shader Designer from what I recall of Render Monkey it had a way to define your own attributes (now as "in" for vertex shaders >= 330) easily though I can't remember to what extent. Shader Designer requires a plugin that I didn't even bother to look at creating cause it's an external process and plugin. Are there any tools out there that support a scripting language and I could easily provide specific input such as float movement = sin(elapsedTime()); and then define in float movement; in the vertex shader ?

It'd be cool if anyone could share how they develop shaders, if they just code away and then plug it into their game hoping to get the result they wanted.


texts: How to prevent multiple playing sounds from destroying your hearing?

texts:
The problem is that when I play 100 sounds almost at same time, all I hear is noise. It's not very attractive to listen it for 30 minutes straight.

I tried to fix this by allowing only 1 sound of each sound type to be played at once. But it still sounds really ugly; eventually my brain keeps hearing only the very end of the shot sounds (or the start of it?), and that gets on my nerves really quickly. Eventually I would just decide to turn off the sounds completely. So is there any point of using sounds in a game like this at all?

How does our dear reality handle this problem? If there is a war out there, how does it sound when hundred of men shoot almost at the same times?

Edit: Here is how the game sounds currently; there isn't even 100 sounds playing at once, maybe 20? http://www.speedyshare.com/VTBDw/headache.mp3 At the beginning it sounds OK, but then it becomes unbearable! In that audio clip there is allowed only 1 sound to be played at once, so it will stop the previous playing sound when new sound is played.

Edit2: And here is same headache but 32 simultaneous sounds allowed to be played at same time: http://www.speedyshare.com/TuWAR/headache-worse.mp3 Quite a torture, eh?


texts:
What's the fastest way to highlight all possible movement tiles for a player on a square grid? Players can only move up, down, left, right. Tiles can cost more than one movement, multiple levels are available to move, and players can be larger than one tile. Think of games like Fire Emblem, Front Mission, and XCOM.

My first thought was to recursively search for connecting tiles. This quickly demonstrated many shortcomings when blockers, movement costs, and other features were added into the mix.

My second thought was to use an A* pathfinding algorithm to check all tiles presumed valid. Presumed valid tiles would come from an algorithm that generates a diamond of tiles from the player's speed (see example here http://jsfiddle.net/truefreestyle/Suww8/9/). Problem is this seems a little slow and expensive. Is there a faster way?

Edit: In Lua for Corona SDK, I integrated the following movement generation controller. I've linked to a Gist here because the solution is around 90 lines of code.

https://gist.github.com/ashblue/5546009


texts: Random/procedural generation of puzzle-platform levels

texts:
I have an idea for a puzzle-platform game where the levels would be randomly generated. Creating a random generation is relatively simple. What's not easy is checking that randomly generated level to see if it's possible to complete, or generating a level where completion is possible. I think there are a number of different ways to do this.

Are there any games that employ something like this? How is something like this typically done, if ever?


texts: Board-Games Design: Physical vs Digital?

texts:
Is there any difference when learning the designing of a physical board-game and digital board game, meaning if I watch a tutorial about a physical board-game design is it applicable on a digital one?

Note: I'm focusing only on design process, not the art-design, only on the gameplay-design (rules, levels, obstacles, etc).


texts:
I'm in the process of optimizing my application memory consumption.
To do so, I'm using Unity profiler while connecting to an Android device, which runs a development build of the application.

The application is using two types of sprite containers:

Sprite sheets created by the Texture packer.
Sprite Atlases created by unity.

Using the profiler, it is observed that while the sprite sheets (created by the Texture packer) take the expected amount of RAM, the sprite atlases created by unity consume DOUBLE the expected amount of RAM.

For example, the sprite atlas UIATLAS, whose size is 4096x4096 is supposed to consume 16MB of RAM:

But looking at the profiler, after running "Take Sample", you see the value 32MB:

My sprite atlas settings are:

Any help is welcome here.

One more comment (please review): UIAtlas belongs to an asset bundle called "atlas_ui". It is defined on several directories containing its sprites, all of which belong to the same asset bundle, atlas_ui. Is that the correct way to define it?

Thanks in advance!


texts: Marketing games for the android - what are the best sites to contact for reviews/advertising?

texts:
WE are in final dev stages of our latest game and want to release it for the android market.
What are the best sites to contact for reviews/advertising that specifically target the android users???


texts: How do I add the "tween-engine-api" to my libGDX game?

texts:
I finished now my first game at LibGDX (I am using Eclipse). I run the game in the desktop launcher and it works. I now want to run my game on Android and iOS.

From some guides I have read, I understand that for running the game on devices I must have the tween-engine library in my project. I tried but couldn't add it to my project.

Can someone help me? (I already tried to do that at "add jars", but it only shows me my project and not the tween-engine library)


texts: SceneKit flickering with Ambient and Omnidirectional lights

texts:
I have a project where I have a sphere with a png texture that represents a planet (or a moon in the videos I'm attaching).

Wrapped around that sphere I have a hexasphere (implemented using the results of my question from last year: How to orient a hexagonal tile on a geodesic sphere (Goldberg polyhedron)?).

Almost everything works just fine however I've noticed that in some situations, the hexasphere flickers at some points.

From my experiments, it seems that the problem is the lighting I am using.

The hierarchy of nodes I have is as follows:

bodyContainer    OMNI
    planet         OMNI (sphere, radius:0.987 with image texture as it's only (diffuse) material)
    hexasphere   AMBIENT (hexasphere, radius: 1.0 as described in the linked question)

There are two light sources, both placed at the centre of the "sun" in my larger model.  OMNI is an Omnidirectional light source with default settings.  AMBIENT is an Ambient light source.

The reason that "body" uses OMNI is that I want the planet or moon to have a light and dark side which changes as the body orbits the sun.

The hexasphere that is co-located with the body by being a sibling of the body in the same container.  It needs to use the AMBIENT light source so that it is equally visible on the dark side of the planet or moon.

What I'm noticing, it that when I move the camera further away from the planet, the parts of the hexasphere closest to the camera seem to flicker, and I seem to be able to see through to some of the hexasphere's cells on the opposite of the sphere.

Here are some videos to show what I'm seeing.

This first shows the scene in it's full 'glory' with all nodes in play as described above:

https://youtu.be/o3hdpuLoSbQ

This next one shows the same hierarchy, however I've changed the planet body to use the AMBIENT light instead.  Note that there is no flicker, but also, I've lost the dark/light side of the planet.

https://youtu.be/O0Ca-MrYgJc

In this 3rd video, I've replaced the body texture with a simple translucent blue color, and reverted to using the OMNI light.  It looks great, but the flickering is back.

https://youtu.be/ftGWnaqoN5I

Finally, I've changed back to the AMBIENT light again, but kept the blue body texture.  Note that the flickering is gone again.

https://youtu.be/c6i5vjOEauw

I'm quite positive that this is something I can fix, but I don't understand yet how.  Is this simply a weakness in the lighting mechanisms in SceneKit?

Is there something special I should be doing to allow the outer hexasphere to render cleanly (i.e. without the flickering), with the ambient light, whilst having the inner sphere that is using an omni light?

UPDATE

I've found one solution that appears to work, however I'm not sure if this will result in a lower quality visual overall.  If I set the material property litPerPixel to NO, then the problem I've outlined goes away.  I'm just not sure that the presumed "lower quality" rendering might cause other problems elsewhere.


texts: Z-order curve — how to query all nearest neighbors?

texts:
TLDR: How to query all nearest neighbors with the least effort? (Iterating over a bigger neighboring area that's continuous and filtering out elements that are not immediate neighbors?)

Suppose the following situation:

You have a set of 3D points' discrete-grid locations stored in a 1D array (an OpenCL buffer)
You've assigned each point its Z-index/Morton code
You sort the array according the Z-indexes
You generate a lookup-array containing the beginning and end indices of continuous regions of same-Z-index-value particles in the first array

Next suppose that you have an OpenCL kernel which executes for each individual particle. And in that kernel you need to loop over all nearest neighboring particles – not only grid cells – (including the currently processed particle itself) of the currently processed particle (that could be 9 neighbors for 2D case, or 27 for 3D).

All of the neighboring particles (for a processed particle) are stored in the nearest-neighboring grid cells. Note that the number of particles in one cell can be high (e.g. look at the bottom-right cells of the image below).

Question: How can I iterate through all the neighboring particles (ideally in a continuous manner)? If this couldn't be solved via Z-order curve, what other approaches can I use?

Example pseudocode:

__kernel void process_stuff(...) {
  foreach ( neighboring_particles ) {  // <- how to achieve this efficiently?
    // perform computation
  }
}

Image legend:

Red line = Z-order curve
The blue dot = the currently processed particle
Yellow dots = another particles
Green region = the current particle neighborhood – a set of particles I need to iterate through


texts: Just 2 images on a window loaded using DirectX10...But how?

texts:
I am a beginner to DX and I have tried looking everywhere for something very similar to this concept but can't find anything.

I just want two rectangles on a window.

Rectangle 1 : on some x,y with some width and height with background as a PNG image
Rectangle 2 : on some x,y with some width and height with background as a PNG image

And one other thing. I am trying to make it so that the image doesn't resize as I resize the window as this makes the pictures really blurry as they get bigger.

I know this is not the type of question that stack likes, but if you can give me some example that does this, I would be very delighted.

Thank you so much.


texts: Annoying snag when moving with dx and dy JAVA

texts:
I am currently using a keyAdapter with detectors and when I move I change the value of dx and dy respectively. However if I move left then right or up then down quickly, the sprite won't move in the direction I last input. Does anyone know a fix?

Detector method:

@Override
public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = -1;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 1;
    }

    if (key == KeyEvent.VK_UP) {
        dy = -1;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 1;
    }
}

@Override
public void keyReleased(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = 0;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 0;
    }

    if (key == KeyEvent.VK_UP) {
        dy = 0;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 0;
    }
}

Move method:

public void move(){
    worldX+=dx;
    worldY+=dy;
}


texts: How to reduce the time taken to path-find to an unreachable location?

texts:
I have a 2048x2048 map and if I path-find to an unreachable location, it makes the pathfinder go through every node on the map which freezes the thread for 4 seconds.

How can I reduce that time?

I'm using JPS
It's a dynamic map (it changes at runtime)


texts: How can I rotate a sphere in response to mouse movement?

texts:
I'm using jMonkeyEngine to develop a game. I'm good at scripting, but math usually goes over my head. I tried the Wiki page for Quaternion, but I was far too confused to figure this out myself :P

My goal

I have a sphere with physics enabled, and I want to have it rotate based on mouse axis movement. I've got listeners set up properly so that in this method:

void roll(int axis, float tpf) {
    Quaternion rot = this.getPhysicsRotation();
    switch(axis) {
        case MouseInput.AXIS_X:
            // Rotate here
            break;
        case MouseInput.AXIS_Y:
            // Rotate here
            break;
    }
}

an axis and a value (+/-) will be provided. Once I figure out how to modify Quaternions, I'll just use RigidBodyControl.setPhysicsRotation(Quaternion) to update the rotation.

My Problem

I'm clueless about Quaternions.. I don't even know what method I'd be using. I assume Quaternion.add() or .mult() will be necessary.

Someone please help! Here's a link to jme's Quaternion class for reference.

Solution

From Zoltan's answer:

void roll(int axis, float tpf) {
    tpf *= 10;
    System.out.println("roll("+axis+","+tpf+")");
    switch(axis) {
        case MouseInput.AXIS_Y:
            Quaternion quaternion = new Quaternion();
            this.setPhysicsRotation(getPhysicsRotation().mult(quaternion.fromAngleAxis(tpf, Vector3f.UNIT_X)));
            break;
        case MouseInput.AXIS_X:
            Quaternion q = new Quaternion();
            this.setPhysicsRotation(getPhysicsRotation().mult(q.fromAngleAxis(tpf, Vector3f.UNIT_Y)));
            break;
    }
}

I'm not quite sure why case:MouseInput had to be swapped, but it works this way so.. shrug


texts: How can I run a Unity game in a window larger than the desktop resolution?

texts:
I am exploring a research problem using Unity. I require a game resolution of at least 4096 x 786. There seems to be no option under build settings for setting a fixed screen size window. (The default screen width and height options are unhelpful here.)

How can I make a window even larger than the desktop?


texts: Simulating 3D height in 2D scene (also shadows)

texts:
I recently stumbled across this http://vimeo.com/99118680 video and was stunned by the beautiful painted art and colors. But mostly I couldn't believe how everything appeared to have three dimensions despite all being 2D images and sprites. I've dug through the creator's blog and couldn't find any helpful ideas on how they managed this effect so I'm giving it a shot here.

My question is about the trees mostly: How could I go about making a tree out of 2D sprites that will orient correctly as if in 3D.

In addition if anyone has any ideas on how they did the shadows I would love to know that also (I feel like they are static but can't be sure).


texts: How to draw to a surface, then draw that surface to the screen

texts:
i have a 2D MonoGame Game (using DirectX), that was originally an XNA game. It involves prerendered shadows (they are Texture2Ds drawn with SpriteBatch.draw). Right now the shadows are being drawn with an alpha value, so overlapping shadows appear darker. This is NOT what i want. Overlapping shadows should be the same shade of black.

So what i want to do is draw all these shadows to a surface, such that the shadows are completely black (alpha == 255), and the surface background is completely transparent (alpha == 0), and then take that surface and draw it to the screen using Color.White*0.25f to give alpha to the shadows at the end.

I'm not sure how to switch rendering targets, or whatever the terminology is, and go about this. Can someone help?

what ive tried so far:

GraphicsDevice.SetRenderTarget(RENTAR); // RENTAR is the name of my RenderTarget2D
GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true }; // not really sure what this does but it was in examples
GraphicsDevice.Clear(Color.White*0.0f); // i clear it with a totally transparent white background, in other words, white with alpha == 0

// now draw shadows normally, but instead of Color.White*0.25f, i use Color.White so that the black shadows are drawn completely black, with no alpha

GraphicsDevice.SetRenderTarget(null); // switch render target back to the screen
SpriteBatch.Draw(RENTAR, new Rectangle(0, 0, 800, 600), Color.White*0.25f); // see i added the "*0.25f" to try to draw this texture with alpha, but it comes out totally blank

So all of this works except that the shadows end up being completely black. I want them completely black in the RenderTarget, so that they dont overlap with any darker shades, and then i want to draw the final RenderTarget on the screen with an alpha of 0.25f, hence "Color.White*0.25f" in the final spritebatch draw. But its as if that 0.25f doesn't exit.


texts:
I was trying to implement a particle system using PointSprites. Draw calls return D3D_OK but I don't see any particle on the screen. I'm not using Vertex Buffer for the particles, but I use two vectors of vertices and I call the DrawPrimitiveUP function. This is my code:

            CreatePntVertices();

            pD3DD -> SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
            pD3DD -> SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
            pD3DD -> SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);

            pD3DD -> SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
            pD3DD -> SetRenderState(D3DRS_ZENABLE, FALSE);

            pD3DD -> SetRenderState(D3DRS_LIGHTING, FALSE);

            pD3DD -> SetFVF(FVF_PNTVERTEX);
            pD3DD -> SetTexture(0, pTex[TEX_POINT]);

            pD3DD -> SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
            pD3DD -> SetRenderState(D3DRS_POINTSCALEENABLE, TRUE);

            pD3DD -> SetRenderState(D3DRS_POINTSCALE_A, 0.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSCALE_B, 0.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSCALE_C, 1.0f);

            pD3DD -> SetRenderState(D3DRS_POINTSIZE, 20.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSIZE_MIN, 3.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSIZE_MAX, 50.0f);

            D3DXMatrixIdentity(&mWorld);
            pD3DD -> SetTransform(D3DTS_WORLD, &mWorld);

            pD3DD -> DrawPrimitiveUP(D3DPT_POINTLIST, pntPlanets.size(), (PVOID)pntPlanets.data(), sizeof(PNTVERTEX));

            pD3DD -> SetRenderState(D3DRS_POINTSIZE, 40.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSIZE_MIN, 9.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSIZE_MAX, 70.0f);

            pD3DD -> DrawPrimitiveUP(D3DPT_POINTLIST, pntStars.size(), (PVOID)pntStars.data(), sizeof(PNTVERTEX));

            pD3DD -> SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);

            pD3DD -> SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
            pD3DD -> SetRenderState(D3DRS_POINTSPRITEENABLE, FALSE);
            pD3DD -> SetRenderState(D3DRS_POINTSCALEENABLE, FALSE);

CreatePntVertices() is a function that set the position of objects and their color into two vectors of PNTVERTEX (pntStars and pntPlanets). pTex is an array of textures. mWorld is a D3DXMATRIX. pD3DD is the Device. FVF_PNTVERTEX is set as (D3DFVF_XYZ | D3DFVF_DIFFUSE). I really don't know why it doesn't work, I tried everything to make it work. Maybe, should I use a dynamic vertex buffer instead?


texts:
try {
            Thread.sleep( (long) ((lastTime - System.nanoTime() + ns) /1000000) );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

The above code seems to catch a negitive timeout value whenever I close out the program. How do I fix it?


texts: How can I manually advance a timeline in GameMaker?

texts:
I have a timeline from 0 to 300 frames divided into maybe 20 different steps.

When I certain condition is met, I want to jump to the next step of that timeline. How can I do that?


texts: How can I support direct P2P for mobile devices?

texts:
I'm Interested in two or more player co-op in Godot, via direct P2P without connection to a central server.
I have this idea that would utilize two smartphones in proximity to one another. I don't know an awful lot about Bluetooth or networking so please explain simply.


texts: How to limit resolutions display in monogame

texts:
I can Add resolutions to the list. Here is part of code.

List<Vector2> resolutions = new List<Vector2>();
foreach (var item in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
{

    for (int i = 0; i < item.Width; i++)
    {
        for (int z = 0; z < item.Height; z++)
        {

            resolutions.Add(new Vector2(i,z));
        }
    }
}

That is all great and dandy...but i wanna for example remove 320x200 up to 1024x768? Is there is any way to do that and how can i set/see refresh rate?


texts: How do you determine which object/surface the user's pointing at with lwjgl?

texts: Title pretty much says it all. I'm working on a simple 'lets get used to lwjgl' project involving manipulation of a rubik's cube, and I can't figure out how to tell which side/square the user's pointing at.


texts: How do you manage / collaborate on a project in Unreal with Developers and Designers?

texts:
We have a team of 3 designers and 2 developers with no prior industry experience working on a Unreal Engine 4 project. The designers will be creating assets & laying the scene out in the editor while developers work on the functionalities in C++ side. What's a general strategy of partitioning work for such setup? More specifically, how do you have the team collaborating so that the project can be worked in parallel with minimal conflicts?

I understand that you can partition the map into sublevels and make sure that only one sublevel is being worked at a time. Well, what if you needed the designer to modify the scene while the developer adds some functionality to a sublevel? Is this not possible in Unreal?

Then there's the matter of source control. Ideally, I'd like to setup a git repository but the designers probably doesn't know how git works at all. Do game companies generally educate the designers so that they at least have working knowledge of source control to do what they need?

I'm just very confused about what the proper workflow should be.


texts: Is Time.deltaTime the last frame time or it is the time difference between frames?

texts:
I just came across the unity blog and found that unity 2020.2 trying to fix Time.deltaTime which is good for more smooth movement (correct me if I am wrong). But when I am reading the blog I found this thing:

In layman’s terms, delta time is the amount of time your last frame
took to complete.

Then, i realized i don't know what exactly the delta time is because i was thing that it actually the difference between the two frame. Then, i consult the unity docs again and find this thing
The completion time in seconds since the last frame (Read Only).

the second line telling something different (isn't it?) which i am thinking is the defination of deltaTime
This property provides the time between the current and previous frame.

I try to understand it through an example:
time - difference:
4
5 (1)
6 (1)
6 (0)
5 (1)
3 (2)
If you see the above what will be the delta time?


texts: I'm writing my own small-time game from scratch, and now I'm looking to start creating models. I've been wondering- what is the best model format to use? Given that I will be writing the model loading code myself and using whatever program generates them. Ideally, I'd look for a format that has fairly wide support between modelling programs, so I can pick the one I like most to actually perform the building, and the format itself would be relatively simple to load, rather than having all of the latest features.


texts: Ideal scheduler on the operating system for games?

texts:
In linux, the preferred scheduler is CFS (correct me if I'm wrong), I'm not sure what the preferred scheduler is on Windows. It's possible to change the scheduler in linux, even after you boot. I'm not sure if this feature exists on Windows or if Microsoft has made this feature available to developers.
Are there schedulers that are a better fit for games - i.e. give better guarantees on latency, working with semi-fair schedulers (like with gpus), etc.? What assumptions does CFS or the Windows scheduler make that are well suited for gaming and which ones can be changed to better suit gaming needs? Is there one that is commercially available or is this something that is still being (actively?) researched?


texts: Unity LWRP alternatives for camera stacking

texts:
I am working on upgrading a project in unity from a 2018 version to the latest 2019. One of the mechanics of the game is an AR (augmented reality) system. Some of the UI elements appear in the 3D world, but clearly as part of the hud. They need to be transformed as the camera moves, but should always be drawn on top of the 3d scene.

The old project achieved this via camera stacking. All the AR elements were drawn on a different camera which rendered on top of the 3D camera. The clear flags were set to "depth only" and it removed all other elements from that camera.

In the 2019 version of Unity with the Lightweight Render Pipeline (LWRP), the clear flags feature on the camera is missing. To the best of my research, camera stacking has been removed from LWRP.

What are my alternatives? How can I now achieve this effect? I would like to stick to LWRP as I am using Shader Graph for many of the effects in the game.


texts: D3D11 - Setting multiple ID3D11SamplerStates for the pixel shader stage once and leaving them be

texts:
In my Direct3D 11 application, I am using several sampler states to retrieve texture data. Some of them are used in all pixel shaders, some of them are only used in very specific ones.

The question may seem simple, but I was not able to find any decent information on the topic-

Are there any penalties (performance or otherwise) involved in creating a number of sampler states for the pixel shader stage of D3D11, setting them all at once and just never touching them again? My shaders would reference these samplers in HLSL if they need them (for instance some shaders would reference SamplerState linear_sampler : register(s0); while some others would reference SamplerState point_sampler : register(s1);, possibly without referencing s0 at all.

Also, is it correct, that if I never want to reference these samplers in my c++ code after creation and setting, I could just release my own external references after they are set and they will not get destroyed, as D3D is keeping internal references as long as they are "bound"(?) ?
And even if had to somehow get a reference, I could simply use ID3D11DeviceContext::PSGetSamplers (of course accepting the involved performance penalty of the lookup), correct?


texts:
I'm trying to make a bullet penetration system. Taking a look at the picture below could help explain what I want better.

If we know the coordinates of a square shape as well as AB vector with direction coefficient, how do we find X,Y for C point?

Basically I'm trying to find the X,Y coordinates of the point of the opposite side of an object of another point. As you can see I'm not exactly going for realism as it's linear. Below are a couple more examples to clarify my objective.

===========================================================================

Any help is greatly appreciated :D


texts:
I am using the following code for moving a capsule:
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);

I am using the following code for the camera, which is a child of the capsule. (xRotation is intialized to 0.0f, and playerBody is a transform):
        float mouseX = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

The character is always moving in the same direction, ignoring the rotation. How can I fix this?


texts: How do I get current emission intensity of a material in code?

texts:
I'm unable to find how can I get current intensity level of emission in Unity.
Is there some kind of method that can return its value?
I need it to complete my algorithm's formula:
current_color = (intensity * 10)/20;


texts: How can I make video games if I don't like programming?

texts:
I am studying C++ code in my school (my major is computer programming). Honestly, my grades are not so good, and assignments are really hard. Sometimes I feel sad that I will spend 8-10 hours per day coding (which is stressful) in the future for my job.

But I still want to make video games. Maybe this is the only reason why I am taking all of these stressful courses. I always write down plots, stories, characters, fictional gaming worlds... Once, I thought I should study artistic technology such as game design and not computer technology such as C++, C#, etc.

However, most of popular game designers (or directors) such as Kojima, Miyamoto, etc. used to be good programmers. Companies actaully assign programmers to directors because they understand how to make a game.

I've try to find other colleges or universities where they teach game design programs. However, one article that lists rank 10 game design schools in North America seems untrustful because the survey company only scores it from intervews of students.

Once, I tried to attend Art Institute of Vancouver which is rank 7 according to that article. However, one programmer who used to be an instructor in there told me the truth: the employement rate of graduated students is low.

How can I have a future making games if I don't like programming?


texts: Connecting to external computer with lidgren

texts:
I'm new to networking and thought i'd muck around a bit with lidgren before i start implementing it in my games, so i made a little client/server chat program that works fine on localhost and lan. I can connect other computers on my subnet and chat, but when it comes to connecting a friends computer not connected on my home network it becomes a bit tricky. I set up UPnP and port forwarding on the server application and i connect the client directly using my external IP address, but the problem seems to come from connecting my client with my external IP address as they never actually connect.

        Network.config = new NetPeerConfiguration("SKGCHAT");
        Network.config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
        Network.client = new NetClient(Network.config);
        Network.client.Start();
        Network.outMsg = Network.client.CreateMessage();
        Network.outMsg.Write("password");
        Network.client.Connect("121.217.195.105", 14242, Network.outMsg); //doesnt work
        //Network.client.Connect("192.168.0.14", 14242, Network.outMsg); works
        //Network.client.DiscoverLocalPeers(14242); works

This is the client initialisation

        Network.config = new NetPeerConfiguration("SKGCHAT");
        Network.config.Port = 14242;
        Network.config.EnableUPnP = true;
        Network.config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
        Network.config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
        Network.server = new NetServer(Network.config);
        Network.server.Start();
        Network.server.UPnP.ForwardPort(14242, "SKG Chat bb");

and this is the server initialisation

This following code should display a message to the server if it even receives the clients connection attempt but when run, no connection attempts are received.

 case NetIncomingMessageType.ConnectionApproval: //wan
                    string message = incMsg.ReadString();
                    outMsg = server.CreateMessage();
                    outMsg.Write("You've been received");
                    server.SendUnconnectedMessage(outMsg, incMsg.SenderEndPoint);
                    if (message == "password")
                    {
                        incMsg.SenderConnection.Approve();
                        finalMsg = "New Connection";
                        readDiag = true;
                    }
                    else
                    {
                        incMsg.SenderConnection.Deny();
                        finalMsg = "Connection denied";
                        readDiag = true;
                    }
                    break;

I honestly am lost when it comes to networking and have no clue why it isnt connecting. Any help would be greatly appreciated.


texts: Unity light object not affect some parts of a 3D model

texts:
So far I've used Unity only for 2D projects. But now I need to implement a 3D scene in my game. I downloaded a tree model from the asset store and placed it in my scene. I couldn't help but notice that my light objects do not affect some parts of such tree.

It affects the leaves, but the trunk remains dark. Even with a point light right next to the trunk, it doesn't seem to be affected by the light.

The tree I refer to is the Shanty Town one: https://www.assetstore.unity3d.com/en/#!/content/44

Since I don't know much about 3D, I've been meaning to ask if this is normal behavior (the fact that the tree's trunk is not affected by light objects) and if I am expected to see other models with the same issue. Is there a way to fix this? I have someone that will make some 3D models for my game, but now I am concerned that my light objects will not properly work on his models.


texts:
I'm making a platformer game and I'm having some trouble wrapping my head around how to organize my classes. I'm wondering what the best way to have everything interact would be without passing parameters all over the place. I've heard of MVC, but does this apply? Should I look into it more?

Thanks in advance


texts: applying rotation and speed to move user

texts:
My player has a position (vec3), rotation (quaternion) and speed.

I have a fixed time step.  At each tick, I work out from key-state etc what rotation and speed adjustments to make.

How do I now compute the new position?

And how, for the graphics which run at a different framerate, do I compute the the tweening for smooth movement?


texts: How to fix the character flip when using an orthographic camera in libGDX

texts:
I used an orthographic camera to follow the character (player), but the problem is that my character is flipped.  There are no tutorials on how to fix this.  Please help as fast as possible.

Here is my create method:

public void create () {

    batch = new SpriteBatch();
    float width=Gdx.graphics.getWidth();
    float height=Gdx.graphics.getHeight();
    camera=new OrthographicCamera();
    camera.setToOrtho(false,width,height);
    camera.update();
    tiledMap= new TmxMapLoader().load("assets\\untitled.tmx");
    tiledMapRenderer=new OrthogonalTiledMapRenderer(tiledMap);
    player=new Player(new Vector2(0,0));
    sr= new ShapeRenderer();

}

Here is my render method:
public void render () {

    Gdx.gl.glClearColor(0, 0, 0.2f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA,GL20.GL_ONE_MINUS_SRC_ALPHA);
    player.update();
    camera.position.set(player.getPosition().x,player.getPosition().y,0);
    camera.update();
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();
    sr.begin(ShapeRenderer.ShapeType.Line);
    sr.setColor(Color.BLUE);
    sr.rect(player.getPosition().x,player.getPosition().y,player.getCurrentFrame().getRegionWidth(),player.getCurrentFrame().getRegionHeight());

    sr.end();
    batch.begin();

    batch.draw(player.getCurrentFrame(),player.getPosition().x, player.getPosition().y);
    batch.setProjectionMatrix(camera.combined);
    batch.end();
}


texts: Parallelism in GPU's rasterization process

texts:
Based on this article I understood the base principle inside the  Rasterization algorithm:

For every triangle
Compute Projection, color at vertices
Setup line equations
Compute bbox, clip bbox to screen limits
For all pixels in bbox
Increment line equations
Compute curentZ
Compute currentColor
If all line equations>0 //pixel [x,y] in triangle
If currentZ<zBuffer[x,y] //pixel is visible
 Framebuffer[x,y]=currentColor
zBuffer[x,y]=currentZ

What I don't understand is how it is implemented in parallel inside the GPU.

I consider 2 possible implementations of the algorithm inside the GPU:

The first way is  drawing every triangle one after the other(in 1 thread) as all of the pixels inside of them are ran in parallel. What bothers me about this way is that it's really slow  for a large amount of triangles.
The second way is drawing every triangle in parallel as for every triangle all the pixels inside of it are ran in parallel too. This looks efficient to me, but I see a problem in the way zBuffer and Framebuffer data are synced as if 2 pixels try to occupy 1 spot there will be 2 threads trying to write on same data at same time. Considering that there are 2 buffers that need to be updated I don't see a way it could happen atomicly.

Another observation I have is that when I draw 2 triangles at same coordinates it's always the last that gets drawn. This stops me from thinking that there's some atomic way of doing pixel calculations as if there were the output pixels of the triangle would be random based of the 2 input triangle colors.

The thing that I guess is that the implementation is something in the middle of my 2 guesses, but it's there were I give up and ask here.


texts:
My 2D OpenGL game is going to have 5 different types of objects I want to render.

-Text

-unTextured AABBs

-unTextured Polys

-Textured AABBs

-Textured Polys

Text will have its own shader and thats fine.

I want things to be simple to code but not insanely slow either.  I'm willing to do a little bit of batching and texture atlasing for bulk things like Tiles which can be drawn all at once, but otherwise objects will be drawn in an unpredictable order and therefore requires some state switching.

Polys will need a matrix for rotation passed as a uniform but obviously AABBs won't.  So I'm not sure if they need to be separate or not.

One way I thought of uses 3 shaders.  One for text and two for rendering textured and untextured polys and AABBs.  For AABBs I could just pass an identity matrix instead of a rotation matrix.

Another way just has 5 separate shaders.

I'm concerned with the amount of switching between different shaders I'll need to do since I already know my GUI renderer will have to switch between rendering text and AABBs (though I don't expect more than a few dozen total widgets and containers).

Since the tiles will be batched and are by far the most numerous object in my game, I expect an asbolute maximum of less than 150 different draw calls (with shader and texture switches).

Just wondering which approach between the two seems the most sensible or if there's another suggestion.


texts:
I don't think this is quite the same questions as this one but if you disagree feel free to close this :)

With SteamOS being announced yesterday I can see that it's entirely possible that opengl will get a big boost in usage in the near future. Now I already know direct3d11 quite well but I think maybe it's time to learn opengl too.

Are there any good resource for learning modern opengl that are aimed at programmers who already know direct3d11 pretty well. So don't need any education on the concepts and math, just on how to use the API and any important differences?


texts: Why does changing the diffuse color of my model's effect change it for all models?

texts:
I want to change color of individual model in my game. But when I use

  effect.DiffuseColor = newColor

then all of models which were loaded from same model file change color too.

How can I do ?


texts: Sending message to all players in room from Photon server?

texts: I need to send a message to all players in the room from a Photon server. Sending the message from a player would introduce too much latency so I need the server to collect data and distribute messages at a rate of 16/s without a player's influence. Is there a way to do this?


texts: How to make player move only along the line

texts: I am using Line Renderer to draw a line on 2D scene using a path of multiple Transforms. And I want player to move along the line without the ability to get off it, like if he was on a rail. The simplest method I can see is setting a number of invisible walls along the line, so the player couldn't physically move away from the line. But maybe there's better method?


texts: how to recieve a trigger with collider or recieve a trigger with collider in unity

texts:
i know if your object has a Collider you can sense another Collider with OnCollisionEnter function or... and you can sense another collider with trigger with OncollsionEnter function and...
but i want to sense other object with trigger even with collider or even with trigger. i cant sense otherobjects that have triggers. for example i have bullet that as i dont want to collider have any physics i turned it to trigger but how can make a charcter to sense it?

Thank you for helping


texts:
I just would like to know what's the difference between the Matcap shaders used in ZBrush for example and the Bidirectional Radiance Distribution Function shader.

Are there two techniques the same ? Is Matcap done using BRDF or are they different ?


texts:
I'm very new to OpenGL/LWJGL.
I'm reading a lot of VBOs.

I'm sorry if I can't concretise my concern, but i'll try it:

Why should I use VBOs?
Whats the difference between using VBOs and  glBegin() and glEnd()?
My Game is organized like this:

One huge map
some static objects like trees on this map
Enemies and Characters

Enemies and Characters are spawned on the fly

and my gameLoop is like this:
statemanager.render()=>Map.render()

Where Map has an Enemy[] and Character[], where both of them have a Tree of Meshes and Mesh has the Vertex-Arrays.

public class Tree<T>
{
  T data;
  T child;
}
abstract class MoveableObject
{
  Tree<Mesh> meshTree;
  public Vector3f pos;
  public Vector3f rot;
}

public class Mesh
{
  Vector3f[] vertices;
  Vector3f[] colors;
  Vector3f[] normals;
}

Where and how should I setup the VBOs?
For example A map and the statics never change, can I setup a VBO once for them instead of setting it up every frame?

Most OpenGL Tutorials show prototypes of the methods, but never explain the parameters of these methods. It's hard to understand how they actually work, if you've never worked with it before.
(Yes, I alread did that Triangle/Cube Tutorial)


texts: Render object transparent with camera instead changing object render mode

texts: I have a pretty large area where I want to show the floor with 60% transparency using a so-called Opacity camera (an idea). I know I can set mesh rendering mode to transparent and then decrease the alpha value. My question is that, is there any way available to apply mesh transparent rendering setting to my camera instead of the object.


texts: Unity - Global illumination seems no longer applied to static objects on runtime

texts:
First of all I'm newbie with Unity, so please forgive me if the answer of this question is obvious for any experimented developer.

So, in one of my project I have this result while I run the project in the editor:

However, on runtime I get this result:

As you can see, several objects in the scene are no longer lighted. In fact, I noticed that ALL my static objects lost their illumination on runtime. I tried with Windows and WebGL as targets, same result.

As I'm hobbyist, I may provide any info about the project configuration. Better, I can provide the Git link of my project:
https://github.com/Jeanmilost/Unity/tree/master/Survival%20Demo%20Scene

This is a demo project, but in the future I'm interested to create more serious projects, and thus I need to understand why this issue happen. So if someone can point me what I'm doing wrong, I would be very grateful, because I already spent some hours to search the solution, without success.


texts: Matching a chunk of procedurally generated world to a chunk of other world

texts:
Have you read The Chronicles of Amber by Roger Zelazny?

Imagine yourself playing in 3rd person MMO game. You spawn in the world and start to wander around. After some time, when you think, that you've learned the map, you realize, that you are in a place, that you have never seen before. You go back to the last place you were sure you know and it is still there. But the rest of the world has changed and you didn't even notice how did it happen.

I've read about procedural world generation. I've read about Perlin noise and octaves, Simplex noise, Diamond-square algorithm, about simulation of tectonic plates and water erosion. I believe I have some vague understanding of general approach in procedural world generation.

And with this knowledge I have no idea on how can you do something like written above. Every idea that comes to my mind encounters some theoretical problems.
Here are some ideas I can think of:

1) "Reversible" world-generation with a seed number as input and some fully-describing-a-chunk-number

I doubt that it is even possible, but I imagine a function, that will receive a seed and produce a matrix of numbers, upon which chunks are built. And for each unique number there is an unique chunk. And a second function, that gets this unique chunk number and produces a seed, that contains this number. I've tried to make a scheme in the picture below:

2) Making chunks completely random and make a transition between them.

As Aracthor suggested. The benefits of this approach is that it is possible and it doesn't require a magic fuction :)

The cons this approach has in my opinion, is that it's likely not possible to have a diverse world. If you have let's say both archipelago and a continent represented by just one number and it's adjacent chunks, then wouldn't the size of a chunk be equal to continent. And I doubt that it is possible to make good-looking transition between chunks. Am I missing something?

So, in other words, you are developing a MMO with procedurally generated world. But instead of having one world, you have many. What approach would you take to generate worlds and how would you implement transition of player from one world to another without player noticing the transition.

Anyway, I believe you've got the general idea. How would you have done it?


texts: How do you generate tileable Perlin noise?

texts:
Related:

Simple noise generation
Understanding Perlin Noise

I'd like to generate tileable Perlin noise.  I'm working from Paul Bourke's PerlinNoise*() functions, which are like this:

// alpha is the "division factor" (how much to damp subsequent octaves with (usually 2))
// beta is the factor that multiplies your "jump" into the noise (usually 2)
// n is the number of "octaves" to add in
double PerlinNoise2D(double x,double y,double alpha,double beta,int n)
{
   int i;
   double val,sum = 0;
   double p[2],scale = 1;

   p[0] = x;
   p[1] = y;
   for (i=0;i<n;i++) {
      val = noise2(p);
      sum += val / scale;
      scale *= alpha;
      p[0] *= beta;
      p[1] *= beta;
   }
   return(sum);
}

Using code like:

real val = PerlinNoise2D( x,y, 2, 2, 12 ) ; // test

return val*val*skyColor + 2*val*(1-val)*gray + (1-val)*(1-val)*cloudColor ;

Gives sky like

Which isn't tileable.

The pixel values are 0->256 (width and height), and pixel (0,0) uses (x,y)=(0,0) and pixel (256,256) uses (x,y)=(1,1)

How can I make it tileable?


texts: Accessing the Properties of an object already in Scene in Unreal Engine using C++

texts:
I am trying to learn more about raycasting in C++ and am trying to implement raycasts in a mini third-person game I am creating. In order to shoot a raycast, I first need to determine its starting location, which in this case I intend it to be from the center of the third-person camera already built-in.

In order to do that, however, I need to access the properties of the camera already in the scene and store its location in a variable using c++. I am relatively new to unreal so I have no idea how to access an object's properties that's already in the scene using C++.

Any help is appreciated

I am still searching, but I couldn't find a satisfying answer yet.


texts: Manually creating cycles in planar, procedural trees?

texts:
I am creating a procedural map using delaunay triangulation and an MST. I'd like to have a bit more control over my final graph. Like when i was looking looking at the MST I wondered how I can connect specific points of the MST? The following image shows the MST in green and the points I want to connect in red.

I was thinking about traversing from a dead end and counting the steps. When it gets within a certain treshhold add a connection. But this might add a connection when there is still a room closer to it. So I have to check for that as well.

Same goes for entrance, exit and perhaps other important places on the graph. I want to end up with a random yet fun and playable dungeon. There must be proven concepts about controlling a graph for procedural dungeons and I would love to learn from it.


texts: What are some different types of device motion gestures?

texts:
Complex touch events are well-defined and can even be categorised as seen in this Wikipedia article

We have great names for various touch gestures like:

Double-tap
Pinch / Zoom
Long Press
etc.

When it comes to whole-device motion gestures, I can only think of a few:

Shake
Figure-8
Horizontal Slice (ie: quickly move back an forth without rotation)

Is there a similar list for whole-device motion gestures?


texts: Can sprite sheet width and height affect performance?

texts:
Is there any performance difference in the way the images are placed inside a sprite sheet image (for the same total area)?

For example, should I place 50 sprites (50x50 each) in a linear way creating a sheet of dimensions 50x2500px? Or is it better to split into multiple rows, say 10 sprites per row, and get a sheet of dimensions 500x250?

Assume that the graphics are hardware accelerated.


texts:
Possible Duplicate:
  How to make a character jump?

I have been working on a 2D platformer and am trying to implement jumping. At the moment I have it simply teleporting upward and then falling back down:

if(Keyboard.GetState().IsKeyDown(Keys.Space) && !jumping) _position2D.Y -= 64f;

Is there any way to smooth it out and make it more parabolic?


texts: Simulation of ball movement in a 3d landscape. The easiest way?

texts:
I have a landscape(generated via Perlin noise) and a ball. I want the ball to move along the geodesic(implementation of basic physics: gravitation, friction). I thought to do raycast around the ball to the landscape, choose the lowest point and move the ball to this point, but it won't work in every case and it won't allow the ball to jump (with inertia). So, what is the best way/algorithm to implement such feature?

P.S. I don't want to use any libraries.

Thanks.


texts: What does it mean to "release" a game in a country?

texts:
I would like to understand what is the meaning of releasing (or not) a game in a particular country.

See for instance the case of Halo 2. According to this source the game was released in a set of countries (e.g., USA, Germany). I wonder about countries where the game was not 'officially' released. Does it mean that Mexico's market will receive a Halo 2 version that is not localized?

What happens when a game is not officially released in a specific country?


texts: Why Post-Processing v1 not works in WebGL build?

texts:
In my WebGL browser app, i've tried to add Post Processing (first version) stack.

I'm using Unity 2018.4.6f1 (i started 1 years ago to develop this app).

I've added Post Processing Behaviour to my Camera, and this is what i've enabled:

When i run my scene on Chrome or Firefox, Camera appears all black but UI is correctly rendered.

Are there any incompatibility issue using Post Processing and WebGL ?

Thanks


texts:
This is a follow-up on the following thread.

I'm applying a code that will move an object just outside the camera's frustum.
I have used the same code in other projects, and it worked fine.

However, I'm using it with URP now, and I'm experiencing a z-position change while I expected only a x position change.

And I just don't see why it does that.

I have recorded a video here.

If I press the button, the cube should be moved to the left only. But it also moves to the back (z position).

And this is the script that I have applied to the cube in the video:

using System;
using UnityEngine;

public class PlaceOutsideCamera : MonoBehaviour
{
     public void PlaceOutsideFrustum(Transform uTransform, bool uLeft)
    {
        uTransform.position = pPlaceOutsideFrustum(uTransform, uLeft);
    }
    public static Vector3 pPlaceOutsideFrustum(Transform uTransform, bool uLeft)
    {
        var frustumPlanes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
        Ray ray;
        Plane plane;

        if (uLeft)
        {
            // 1.
            ray = Camera.main.ScreenPointToRay(new Vector3(0, Camera.main.pixelHeight / 2f, 0));
            plane = frustumPlanes[0];
        }
        else
        {
            ray = Camera.main.ScreenPointToRay(new Vector3(Camera.main.pixelWidth - 1, Camera.main.pixelHeight / 2f, 0));
            plane = frustumPlanes[1];
        }

        float fDistance = Mathf.Abs(Camera.main.transform.position.z - uTransform.position.z);

        // 2.
        var borderPoint = ray.GetPoint(fDistance);

        // 3.
        var frustumOutside = -plane.normal;

        Bounds b = BoundsFromTransform(uTransform);
        // 4.
        var halfDiameter = b.size.magnitude / 2f;

        return borderPoint + frustumOutside * halfDiameter;
    }
    public static Bounds BoundsFromTransform(Transform uTransform)
    {
        try
        {
            Bounds bounds = new Bounds(uTransform.position, Vector3.zero);//wir hätten auch einfach new Bounds() nehmen können, meint Manfredas

            foreach (Renderer renderer in uTransform.GetComponentsInChildren<Renderer>())
            {
                bounds.Encapsulate(renderer.bounds);
            }

            Vector3 nOff = bounds.center - uTransform.position;

            return new Bounds(nOff, bounds.size);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.Break();
            return new Bounds();
        }
    }
    public void OnGUI()
    {
        if (GUI.Button(new Rect(0, 350, 100, 50), "DoThis!"))
        {
            pDoThis();
        }
    }
    private void pDoThis()
    {
        this.PlaceOutsideFrustum(this.transform, true);
    }

}

Can anybody tell me why my code does this? I just don't see it.
Thank you very much for the help!

Edit: Here is another video that shows the camera position in the Inspector.


texts: How to keep same aspect ratio in different devices with cocos2dx?

texts: I have been making a board game and I am using cocos2dx. There are two scenes for now, One is main menu and the other is gameplay scene. When I run the apk on tablet with EXACT_FIT resolution policy in AppDelegate.cpp sprites in the scene seems stretched out a little bit. How can I maintain the same aspect ration in all devices and also the positions of game entities? Thanks.


texts:
I wish to create a game object where you can start dragging it by touching somewhere on the line of its collision and to create these "dynamic shapes" by stretching the sprites and readjusting the sprite look and collision according to the drag point.

Adding an illustration for clearance:

Started playing with Sprite Shape Renderer to create these curved sprite tiles but I need to be able to create dynamic ones using the mouse cursor and adjust all collisions.

I've tried to add an AnchorDragger script to the Sprite Shape Renderer object:

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

public class AnchorDragger : MonoBehaviour
{
    const int INVALLID_INSERTED_POINT_INDEX = -1;

    public SpriteShapeController spriteShapeController;
    private Spline spline;
    private int inseretedPointIndex = INVALLID_INSERTED_POINT_INDEX;

    void Start()
    {
        spline = spriteShapeController.spline;
        int pointCount = spline.GetPointCount();
        for (var i = 0; i < pointCount; i++)
        {
            Vector3 currentPointPos = spline.GetPosition(i);
            Debug.Log("Point " + i + " position: " + currentPointPos);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (inseretedPointIndex != INVALLID_INSERTED_POINT_INDEX)
        {
            spline = spriteShapeController.spline;
            spline.SetPosition(inseretedPointIndex, Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f)));
            // Debug.Log("Setting position to: " + Camera.main.ScreenToWorldPoint(Input.mousePosition));
        }
    }

    void OnMouseDown()
    {
        Debug.Log("Mouse Down Position:" + Input.mousePosition);
        Vector3 mouseDownPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f));
        Debug.Log("World Position: " + mouseDownPos);
        spline = spriteShapeController.spline;
        int pointCount = spline.GetPointCount();
        int closestPointIndex = int.MaxValue;
        float minDistance = int.MaxValue;
        for (var i = 0; i < pointCount; i++)
        {
            Vector3 currentPointPos = spline.GetPosition(i);
            float distance = Vector3.Distance(currentPointPos, mouseDownPos);
            if (distance < minDistance)
            {
                minDistance = distance;
                closestPointIndex = i;
            }
        }
        spline.InsertPointAt(closestPointIndex, mouseDownPos);
        spline.SetTangentMode(closestPointIndex, ShapeTangentMode.Continuous);
        inseretedPointIndex = closestPointIndex;
        Debug.Log("Inserted point index: " + inseretedPointIndex);
    }

    void OnMouseUp()
    {
        Debug.Log("Mouse Up");
        spline = spriteShapeController.spline;
        spline.RemovePointAt(inseretedPointIndex);
        inseretedPointIndex = INVALLID_INSERTED_POINT_INDEX;
    }
}

Basically tried to figure the closest point on the spline where I've clicked and then inserting a new point and setting its position on Update to where the mouse is and delete the point on mouse up.Right now I'm having a problem where the drag position is not correct for some reason.Where I clicked, where the new point position is set:

Even when I tried to play with where I click and where I take my mouse to while dragging, not sure why, could use help!

Also I'm not sure how I would update the EdgeCollider2D? I know I can get it in the Update method using:

EdgeCollider2D edgeCollider = gameObject.GetComponent<EdgeCollider2D>();

But how would I actually update it correctly to fit the new sprite?


texts: Animations only play when moving along the Y axis

texts:
My problem is, I have walk animations which only play when my character is moving upward or downward, and I don't know why. This is my code:

public float speed = 5f;
private Animator anim;

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

void Update () {
    anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Horizontal")));
    anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Vertical")));

    if (Input.GetAxis ("Horizontal") < -0.1f) {
        transform.localScale = new Vector3 (-1,1,1);
    }
    if (Input.GetAxis ("Horizontal") > 0.1f) {
        transform.localScale = new Vector3 (1,1,1);
    }
}

void FixedUpdate {
    Vector3 move = new Vector3 (Input.GetAxis("Horizontal"), Input.GetAxis ("Vertical"),0);
    transform.position += move*speed*Time.deltaTime;
}


texts: Animator from another gameobject keeps disappearing from script on play

texts:
I am working on a gun script and it worked fine until earlier today when I made a change to the script and it stopped working. I put it back, but for some reason now the animator object attached to the script keeps disappearing.

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

public class RifleShooting : MonoBehaviour
{
    private float NextTimeToFire = 0f;
    private int CurrentAmmo;
    private bool IsReloading = false;

    [Space(10)]
    [Header("Floats")]
    public float Damage = 10.0f;
    public float Range = 100.0f;
    public float ImpactForce = 60f;
    public float FireRate = 15f;
    public float ReloadTime = 1.0f;

    [Space(10)]
    [Header("Others")]
    [Space(5)]

    [Space(10)]
    [Header("Others")]
    [Space(5)]
    public int MaxAmmo = 10;
    public Camera FPSCamera;
    public Animator GunAnimations;
    public ParticleSystem MuzzleFlash;
    public GameObject impactEffect;
    public bool AllowedToShoot = true;
// Start is called before the first frame update
    void Start()
    {
        GunAnimations = GetComponent<Animator>();
        if (CurrentAmmo == -1)
            CurrentAmmo = MaxAmmo;
    }

    private void OnEnable()
    {
       IsReloading = false;
        GunAnimations.SetBool("Reloading", false);
    }
    // Update is called once per frame
    void Update()
    {
        if (IsReloading)
        return;

        if (CurrentAmmo <= 0)
        {
            StartCoroutine(Reload());
            return;
        }

        if (AllowedToShoot == false) return;
        {
            if (Input.GetButton("Fire1") || Input.GetButtonDown("Fire1") && Time.time >= NextTimeToFire)
            {
                NextTimeToFire = Time.time + 1f / FireRate;
                Shoot();
            }
        }
    }

    IEnumerator Reload()
    {
        IsReloading = true;
        Debug.Log("Reloading...");
        GunAnimations.SetBool("Reloading", true);
        GunAnimations.SetBool("IsShooting", false);
        yield return new WaitForSeconds(ReloadTime - .25f);
        GunAnimations.SetBool("Reloading", false);
        yield return new WaitForSeconds(.25f);
        GunAnimations.SetBool("IsShooting", true);
        CurrentAmmo = MaxAmmo;
        IsReloading = false;
    }

    void Shoot()
    {
        //shooting script here
    }
}

Also if it helps here is what I see in the console when I try to fire:

MissingComponentException: There is no 'Animator' attached to the "M4A1" game object, but a script is trying to access it.


texts:
I don't understand why the created mesh is upside down if z ( z*tileSize ) is positive, the mesh is then rendered with the texture looking down. With "-z", the mesh texture is looking up correctly, but it then starts at 0,0,0 and follows his path to the negative values, which I don't want. (I would like the mesh to create tiles in the X/Z axis, not in the X/-Z axis).

Would you know how to fix this? Here is the method to create the mesh : (if I switch the normals to -Vector3.up, the plane texture is still looking down, and it becomes black.)

public void BuildMesh() {
        int numTiles = size_x * size_z;
        int numTris = numTiles * 2;

        int vsize_x = size_x + 1;
        int vsize_z = size_z + 1;
        int numVerts = vsize_x * vsize_z;

        // Generate the mesh data
        Vector3[] vertices = new Vector3[ numVerts ];
        Vector3[] normals = new Vector3[numVerts];
        Vector2[] uv = new Vector2[numVerts];

        int[] triangles = new int[ numTris * 3 ];

        int x, z;
        for(z=0; z < vsize_z; z++) {
            for(x=0; x < vsize_x; x++) {
//HERE
                vertices[ z * vsize_x + x ] = new Vector3( x*tileSize, 0, -z*tileSize );
                normals[ z * vsize_x + x ] = Vector3.up;
                uv[ z * vsize_x + x ] = new Vector2( (float)x / size_x, 1f - (float)z / size_z );
            }
        }

        for(z=0; z < size_z; z++) {
            for(x=0; x < size_x; x++) {
                int squareIndex = z * size_x + x;
                int triOffset = squareIndex * 6;
                triangles[triOffset + 0] = z * vsize_x + x +           0;
                triangles[triOffset + 1] = z * vsize_x + x + vsize_x + 1;
                triangles[triOffset + 2] = z * vsize_x + x + vsize_x + 0;

                triangles[triOffset + 3] = z * vsize_x + x +           0;
                triangles[triOffset + 4] = z * vsize_x + x +           1;
                triangles[triOffset + 5] = z * vsize_x + x + vsize_x + 1;
            }
        }

Thanks


texts: How to use Audio Profiles in Cocos2d Ver 3.3 AudioEngine

texts:
I have 2 audio files that I want to play at different times: background.wav a sneeze.wav.  I believe that I have to convert both wav files into mp3, caf and ogg files.  Then I do this:

static const int FILE_COUNT = 2;
std::string _audioBackgroundFiles[FILE_COUNT];
_audioBackgroundFiles[0] = "background.mp3";
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC
    _audioBackgroundFiles[1] = "background.caf";
#else
    _audioBackgroundFiles[1] = "background.ogg";
#endif

for(int index = 0; index < FILE_COUNT; ++index){
        auto id = AudioEngine::play2d(_files[index], false, 1.0f, &_audioProfile);
}

I don't understand how to create an audio profile?  Do you create a profile for every sound?  I'm very confused.


texts: track how far player is from finish line

texts:
We are developing mobile racing game.We are looking to implement tracking system.

For example if four players are on race track then in up side of screen one slide bar type line will be there whcich will show how far user is from finish line.

Angry birds GO has done similar thing,Check in http://imgur.com/Bhq7jKF

Any suggestion on implementation ?


texts: Why are my colliders offset on my isometric map?

texts:
I'm building an isometric environment in Unity and having some trouble with my colliders aligning with what shows in the scene editor to the reality in gameplay.

There is nothing in the collider component to indicate that it should have any offset, or that there is anything at play other than the default settings.  This goes for all types of 2D colliders I should add.  I did try a 3D collider just out of curiosity, and nothing happens at all.  This has been my experience with multiple objects, not only the one I've highlighted in the picture below.

I'm using the Adventure Creator add-on if that makes any difference.


texts: glDrawElements vs glDrawArrays for polygons that do not reuse vertices

texts:
Is it better to use glDrawElements or glDrawArrays when not reusing vertices?  There must be some difference, otherwise people would always use glDrawElements?

I suppose the question could be reworded as the following:

Does glDrawElements function the same as glDrawArrays if it is passed a blank indices table?