texts: How can I get projected coordinates of vertex on screen

texts:
I want to check picking for faces and for that I need projected X Y coordinates of my vertexes in -1 to 1 range:
For that I multiply my vertex array with matrices and then get projected triangle coordinates from it and check if mouse is inside of that triangle ,but something goes wrong:
Here is my code

    for (int i = 0; i < m_vertexCount; ++i)
{
    D3DXVec4Transform(&m_Pverts1[i], &m_Pverts[i], &worldmatrix);
    D3DXVec4Transform(&m_Pverts1[i], &m_Pverts[i], &viewmatrix);
    D3DXVec4Transform(&m_Pverts1[i], &m_Pverts[i], &projectionmatrix);
}
z = 0;
for (int i = 0; i < m_faceCount; ++i)
{
    x1 = m_Pverts1[m_verts[z].x - 1].x / m_Pverts1[m_verts[z].x - 1].w;
    y1 = m_Pverts1[m_verts[z].x - 1].y / m_Pverts1[m_verts[z].x - 1].w;
    z1 = m_Pverts1[m_verts[z].x - 1].z / m_Pverts1[m_verts[z].x - 1].w; ++z;
    x2 = m_Pverts1[m_verts[z].x - 1].x / m_Pverts1[m_verts[z].x - 1].w;
    y2 = m_Pverts1[m_verts[z].x - 1].y / m_Pverts1[m_verts[z].x - 1].w;
    z2 = m_Pverts1[m_verts[z].x - 1].z / m_Pverts1[m_verts[z].x - 1].w; ++z;
    x3 = m_Pverts1[m_verts[z].x - 1].x / m_Pverts1[m_verts[z].x - 1].w;
    y3 = m_Pverts1[m_verts[z].x - 1].y / m_Pverts1[m_verts[z].x - 1].w;
    z3 = m_Pverts1[m_verts[z].x - 1].z / m_Pverts1[m_verts[z].x - 1].w; ++z;

    //code .. //
}

Where  m_Pverts is array of vertexes  m_Pverts1 is empty array for transformed vertexes and  m_verts[].x is array of vertex indexes:
x1,y1,z1,x2,y2,z3,x3,y3,z3 must be X Y  projected coordinates of triangle and Z depth:
Other code is checked and works right:

What I am doing wrong ??


texts: Change the alpha blending color of scaled textures

texts:
It looks like semitransparent pixels are blended with while color when textures are drawn scaled. It is very noticeable and looks ugly when textures are drawn on dark background.

public class SomeScreen implements Screen {
    private TextureRegion textureRegion;

    @Override
    public void show() {
        // Loading texture
        Texture texture = new Texture(Gdx.files.internal("texture.png"), true);
        // Setting filter to "linear"
        texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
        // Getting the region
        textureRegion = new TextureRegion(texture, 0, 0, 64, 64);
    }

    @Override
    public void render(float delta) {
        // Clearing screen
        Gdx.gl.glClearColor(0.09f, 0.09f, 0.09f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // Drawing textureRegion
        Game.instance.batch.begin();
        Game.instance.batch.draw(textureRegion, 100f, 100f, 256f, 256f); // Actual texture region size is 64x64px
        Game.instance.batch.end();
    }
}

I need to get rid of that white noise around the shape, bud don't know how.

Source image:

Draw results:


texts: Should i be worried about loading so much data?

texts:
So a week ago or so i asked this question:
A few queries about my Map Data (& ideas of improvement, seconded opinion required)

And the advice in the comment was to ask them as 3 separate questions. So I' going to focus on map loading, and my concerns.
So recently i have been working on a new map editor, mainly creating some form of an entity system so that i can easily edit and manage any entities i have (animated tiles, enemies etc.). And i currently have animated tiles done.

But now I'm coming to the point were I'm going to-do the saving and loading in the editor.
And I'm just curious to know if i should be worried about loading quite a-lot of data in some cases.

So this might be an example of things that would be in my map files;

Map Data, the number of layers, the width & height of the map and finally then all the map tile data. (Currently in my old map format,
this is all the data the map's contain!)
Then having any Animated Tile data, their position, what animation file they use.
Enemy Data, the enemy type, positions of the enemies, the starting enemy state.
Level Exit Data, the position of the exit node, the destination of were the exit will take the player.

In terms of scale, i don't think a level will contain more than 20 enemies, in terms of Level Exit data, perhaps 3-4 max. Animation tiles, perhaps 20-40 max depending on the size of the level.

I'm just worried in that by loading up all this data it's going to take quite the hit on performance.
So my question is purely, should i be worried? Or am i just being overly sensitive to loading this much data? In-fact in comparison to other games, is that a-lot of data to be loaded in with a map (that would be an interesting comparison to settle me, to see another games map and perhaps compare the amounts of data stored).

Thanks in advance for any help :)


texts: Unexpected white pixels when using terrain painting brush

texts:
I have two texture layers in my terrain. When I paint the second layer on the base layer the results around some of the the joining areas will be like:

I can remove it by carefully painting over it but in some cases it just grows further and consumes a lot of time and energy. I'm using Unity 2018.4.0f1 and have never seen such thing in older versions and 2019. However I have not used terrains very much. Tell me if you need any information in the comments.
I have tried the following approaches:

Disabling Alpha Channel in texture import settings
Testing both color spaces (Linear and Gamma)
Using the same texture for both layers (The white line still exists)
Using custom Diffuse Material

The problem seems to be the generated SplatAlpha texture:

As you can see four layers are generated: Red, Green and Black. But you can see the pixels I marked with blue and I don't know where are they coming from.
Why is that and how to solve it?


texts:
I have an options screen for things like difficulty, resolution, full-screen, etc., but I'm struggling to find the "best" way to store/obtain these variables at run-time.

Currently, I've implemented a Constants class which contains all the GameOption enums, but how do I choose a default for all of these options? Also, how do I get the currently selected enum?

Regarding the resolution, specifically, I've decided to store the values, but I'm unsure of how to get the default, or currently stored, values. Any direction would be great; thanks! :)

namespace V1.test.RPG
{
  public class GameOptions
  {
    public enum Difficulty { EASY, MEDIUM, HARD }
    public enum Sound { ON, QUIET, OFF }
    public enum Music { ON, QUIET, OFF }
    public enum ResolutionWidth
    {
        SMALL      = 1280,
        MEDIUM     = 1366,
        LARGE      = 1920,
        WIDESCREEN = 2560
    }
    public enum ResolutionHeight
    {
        SMALL      = 800,
        MEDIUM     = 768,
        LARGE      = 1080,
        WIDESCREEN = 1080
    }
    public Boolean fullScreen = false;
  }
}

NB: I asked over at SO and they pointed me to this place. There is a comment there but I'd like to hear different ways of doing it / the most used ways.


texts: Unity 4.6 UI Replace Images on selection in List of buttons[i]

texts:
I made a list containing all the buttons in the UISelectionCanvas and would like to change each image as it is being selected. The problem is once the selection selects a new type of unit it will change all the buttons sprites in the list to the new selection instead of just changing the one selected.

     for a example imagine I have 10 units 9 peasants and 1 warrior

as each peasant is selected the sprite adds the peasant icon to the button. if 8 peasants are selected and then the 9th selection is a warrior it changes all 9 buttons to a warrior icon then if I selects the 10th peasant it changes them all back to peasant.

        for (int i = 0; i < buttons.Count; i++)
        {
            for (int c = 0; c < SelectedUnits.Count; c++)
            {
                if (i <= c)
                {
                   buttons[i].SetActive(true);

                  foreach (var unit in SelectedUnits)
                 {
                   if(unit.tag == "Peasant")
                 {
                    buttons[i].transform.GetComponent<Image>().sprite = peasant as Sprite;
                 }
             else if(unit.tag == "CityGuard")
            {
               buttons[i].transform.GetComponent<Image>().sprite = warrior as Sprite;

          }
        }

      }
      else
      {
      buttons[i].gameObject.SetActive(false);
    }
 }

}


texts: How to I get a rotated sprite to move left or right?

texts:
Using Java/Slick 2D, I'm using the mouse to rotate a sprite on the screen and the directional keys (in this case, WASD) to move the spite. Forwards and backwards is easy, just position += cos(ang)*speed or position -= cos(ang)*speed. But how do I get the sprite to move left or right? I'm thinking it has something to do with adding 90 degrees to the angle or something. Any ideas?

Rotation code:

int mX = Mouse.getX();
        int mY = HEIGHT - Mouse.getY();
        int pX = sprite.x+sprite.image.getWidth()/2;
        int pY = sprite.y+sprite.image.getHeight()/2;
        double mAng;

        if(mX!=pX){
            mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX));
            if(mAng==0 && mX<=pX)
                mAng=180;
        }
        else{
            if(mY>pY)
                mAng=90;
            else
                mAng=270;
        }

        sprite.angle = mAng;
        sprite.image.setRotation((float) mAng);

And the movement code (delta is change in time):

Input input = gc.getInput();

                Vector2f direction = new Vector2f();
                Vector2f velocity = new Vector2f();

                direction.x = (float) Math.cos(Math.toRadians(sprite.angle));
                direction.y = (float) Math.sin(Math.toRadians(sprite.angle));
                if(direction.length()>0)
                    direction = direction.normalise(); //On a separate note, what does this line of code do?

                velocity.x = (float) (direction.x * sprite.moveSpeed);
                velocity.y = (float) (direction.y * sprite.moveSpeed);

                if(input.isKeyDown(sprite.up)){
                    sprite.x += velocity.x*delta;
                    sprite.y += velocity.y*delta;
                }if (input.isKeyDown(sprite.down)){
                    sprite.x -= velocity.x*delta;
                    sprite.y -= velocity.y*delta;
                }if (input.isKeyDown(sprite.left)){
                    //???
                }if (input.isKeyDown(sprite.right)){
                    //???
                }


texts: When trying to render a texture in opengl after including the stb_image.h file in the project i get a linker error

texts: Initially i gave the path of the stb_image.h & stb_image.c file location C/C++ include directories as adding the header file directly to the project was not working.


texts: Assigning Objects when duplicated in the editor?

texts:
I'm wondering if there is a way to have an Object when duplicated in the editor assign a GameObject variable to the newly duplicated version of itself. Is there an option in Unity or do I have to code it out.

So I would like it to follow these steps:

So I would have the old GameObject with the variable named "nextStop" with nothing assigned to it.
Then I duplicate said object and the older object's variable is assigned to the newly duplicated object.
Done.

I'm doing this for a rail editor to make it easier to create new rails to follow.

I would like not to have to assign to each and every Object it will make things so much easier to explain for others to use. "Just duplicate these objects."

And in case you need it and Unity doesn't already have an option built in here's my code for the track.

using UnityEngine;
using System.Collections;

public class Rails : MonoBehaviour {

    public GameObject nextStop;
    LineRenderer myLine;
    public bool endLevel = false;
    public Train myShip;
    void OnDrawGizmos()
    {
        if (nextStop) {
            Gizmos.color = Color.green;
            Gizmos.DrawLine(transform.position, nextStop.transform.position);
        }
    }
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "train")
        {
            if (nextStop)
            myShip.track = nextStop;
            if (endLevel)
            {
                // Load the next level
            }
        }
    }
}

Oh yeah I should mention I have little experience modifying code to do things in the editor.


texts:
In my current project I am creating a 2d game (rpg) which should be able to dynamically create new weapons and armor based on different components. So, i.e. a sample weapon would consist of barrel1, grip3, etc. It's much like Borderlands, but in 2d.

I thought about using a library like CImg in order to assemble the different parts (which are images) and then using the created sprite in my game.

Am I on the right way? Is there a better way to accomplish this task?


texts: Clicking in a UI Button activate another

texts:
I'm new to unity and creating my first game to learn more about it. Now i got a problem wich i click on a button and sometimes another button active, for example: i press "Options" on pause menu and it active "Restart" or the "Main Menu".
if someone can help me, I appreciate it.
I set them up like this, if there's any error or need more info please let me know. And in the first image i tried split in 2 canvas, but didn't work.
P.S.: It happens even with buttons with no actions or scripts on them.

public void OnPause()
{
    Time.timeScale = 0;
    isPaused = true;
    unPauseButton.SetActive(true);
    pauseButton.SetActive(false);
    PauseGameMenu.SetActive(true);

    GameObject.Find("PowerUpSpawner").GetComponent<PowerUpManager>().enabled = false;

}
public void UnPause()
{
    Time.timeScale = 1;
    pauseButton.SetActive(true);
    unPauseButton.SetActive(false);
    PauseGameMenu.SetActive(false);
    GameObject.Find("PowerUpSpawner").GetComponent<PowerUpManager>().enabled = true;
    isPaused = false;

}


texts: Make standard Unity 3D objects non transparent

texts: I have a problem. When I add a cube or sphere to the scene they are transparent. How can I disable it? I tried adding materials, but it didn`t help and even if it would have helped it still a very dumb way of making standard objects non transparent.


texts: How can i prevent objects faces clipping over other objects faces?

texts:
I have a naked body, I have a bra over that body, I have a suit over that bra.

Since the objects arent accurate enough, i get ugly "clipping".
Is there a way or method I can prevent this? (except messing with the Scale)

Like a shader which gives out a Render-Queue to faces near other faces... and does always render first ... if the rendered item is near enough.


texts: Unity - Manually sync location of players from server to client

texts:
I am new to Unity networking. I've set up my scene with NetworkManager and the Player prefab having NetworkIdentity. I originally had my players set up to sync with a NetworkTransform. This worked, but the objects were very choppy whenever they were children of a moving object.

In order to fix this issue, I've replaced NetworkTransform with a class extending NetworkBehavior, using UnityEngine.Networking, and containing the following code to sync localPosition:

void Update () {
    CmdSyncPos (transform.localPosition, transform.localRotation);
}

[Command]
protected void CmdSyncPos (Vector3 localPos, Quaternion localRotation) {
    transform.localPosition = localPos;
    transform.localRotation = localRotation;
}

This works really well! The only problem is that this is one-way, the server now has the updated position of all clients but the clients only have the updated  versions of themselves.

How can I do this in reverse: Manually sync the location of non-local players from server to client?


texts: How should I detect whether or not to enable Anti-Aliasing?

texts: How can I detect the speed of the user's graphics card so that I can decide whether or not to enable advanced graphics features that would slow down the app on a slow card, such as anti-aliasing? I am using OpenGL.


texts: Splitting a tetris game apart - where to put time-management?

texts:
I am creating a tetris game in C++ & SDL, and I'm trying to do it "good" by making it object-oriented and keeping scopes small. So far I have the following structure:

A main with some lowlevel SDL set up and handling input
A game class that keeps track of score and provides the interface for main (move block down, etc)
A map class that keeps track of the current game field, which blocks are where. Used by the game class.
A block class that consists of the current falling block, used by game.
A renderer class abstracting low level SDL to a format where you render "tetris blocks". Used by map and block.

Now I have a though time where to place the time-management of this game. For example, where should be decided when a block bumps the bottom of the screen how long it takes the current block locks in place and a new block spawns?

I also have an other unrelated question, is there some place where you can find some standard data on tetris like standard score tables, rulesets, timings, etc?


texts: How to generate a 2D tile planet with perlin noise?

texts:
I recently tried reading about procedurally generating and I found out that perlin noise is probably a good way to do it.

Now one way of generating 2D terrain would be to have 2D perlin noise and depending on the height of the noise at a certain point place a certain tile. My question is now, how could I modify the perlin noise so that it generates a planet? It would probably need to be a circle, in the middle of which the noise is high, while outside of the circle its pretty low. The overall shape of the noise would be rectangular.

In the end it should look something like this, but noisy: http://i.imgur.com/a7zaVFa.png

Any advice or articles that help?


texts: Implementing acceleration in topdown 2d game

texts:
So I'm making this topdown game and I'm trying to implement player control movement so that it feels more natural. Right now I have an update method like this:

void update(float delta) {
    velocity = sf::Vector2f();

    if right:
        velocity.x = 1;
    if left:
        velocity.x = -1;
    if up:
        velocity.y = -1;
    if down:
        velocity.y = 1;

    velocity *= sf::Vector2f(delta, delta);
    position += velocity;
}

I want to implement acceleration, so that the player doesn't reach top speed as soon as they hit a key, as well as de-acceleration so that they slow down (but quicker than they accelerate) as they release the key.

So I remove the velocity being reset to zero, and if they go right I increment the x component of the velocity by the speed and then if they still hold right I increment the speed by acceleration. Then when they release the key I slow down this acceleration, but the way I've done it you move right it works, then you move left and the player goes right again but really fast.

Note that I'm only doing left + right before I move on to up and down since its the same principle, so the code is unfinished:

void Player::update(double delta) {
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
        vel.x += speed;
        speed += accel;
        if (speed > max_accel) {
            speed = max_accel;
        }
    }
    else if (vel.x > 0) {
        speed -= accel;
        if (vel.x <= 0) {
            vel.x = 0;
            speed = accel;
        }
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
        vel.x -= speed;
        speed -= accel;
        if (speed < -max_accel) {
            speed = -max_accel;
        }
    }
    else if (vel.x < 0) {
        vel.x += speed;
        if (vel.x >= 0) {
            vel.x = 0;
            speed = accel;
        }
    }

    pos.x += vel.x * delta;
    pos.y += vel.y * delta;
}

What am I doing wrong here? I can't seem to get the logic right for when you release a key or not. I figured that if they aren't holding A, but their velocity is in the direction of A then we apply the slowdown but I can't seem to figure out how to handle when we actually reach the velocity of zero.


texts:
I have been working on a simple implementation of a card game in object oriented Python/HTML/Javascript and building on the top of Django.

At this point the game is in its final stage of development but, while spotting a big issue about how I was keeping the application state (basically using a global variable), I reached the point that I'm stuck. The thing is that ignoring the design flaw, in a single-threaded environment such as under the Django development server, the game works perfectly.

While I tried to design classes cleanly and keep methods short I now have in front of me an issue that has been keeping me busy for the last 2 days and that countless print statements and visual debugging hasn't helped me spot. The reason I think has to do with some side-effects of functions and to solve it I've been wondering if maybe refactoring the code entirely with static classes that keep no state and just passing the state around might be a good option to keep side-effects under control. Or maybe trying to program it in a functional programming style (although I'm not sure Python allows for a purely functional style).

I feel that now there's already too many layers that the software (which I plan to make incredibly more complex by adding non trivial features) has already become unmanageable.

How would you suggest I re-take control of my code-base that (despite being still only at < 1000 LOC) seems to have taken a life of its own?


texts: Should the server calculate the time of a player's input, or trust sent data?

texts:
I am curious about the details of lag compensation in games. I have read a lot of articles about it, for example:

Source Engine Multiplayer Networking
Fast-Paced Multiplayer - Gabriel Gambetta
How do Multiplayer Game[s] sync their state?

And I still have this question:

At the 1st link, the Valve developers give a formula to compute the time when the command should be executed:

Command Execution Time = Current Server Time - Packet Latency - Client View Interpolation

But on the 3rd site, the author says that the client sends the Command Execution Time and the server does not need to use that complicated formula to calculate something that the client can give the server for free. I mean, the player will always send the correct info about Command Execution Time, so the server can believe him.

Which one is correct? Or are both suitable (for different situations)?


texts: Using single Triggers on multiple controllers in Unity

texts:
After trying out a lot of stuff I finally need to surrender. Im having a project where I want to use the triggers of the Xbox Controllers seperately. To do so I added them as axis 9 and 10 in the input manager (see image). Now, when i have multiple controllers connected on project startup the triggers wont get recognized. I have to press the trigger on two controllers to get a value from it...prettty strange. If i reconnect the controllers after project launch everything works fine...

Test script looks like this.

Thanks!


texts: Why are committed resources better than placed resources?

texts:
This NVIDIA document regarding dos and don'ts in DirectX 12 states the following:

  Use committed resources where possible to give the driver more
  knowledge

  This allows the driver to better manage GPU memory
  A good use case for placed resources are resource heaps that are e.g. used during streaming and do hold different sets of read-only
  textures over their life time

But this raises more questions than it answers:

What additional knowledge is given to the driver if I use a committed resource? The information on the resource that I pass to both CreateCommittedResource and CreatePlacedResource is pretty much the same...
What does it mean that the driver will better manage GPU memory?
If I know what the allocation/deallocation patterns look like in my game, isn't it better if I manage GPU memory manually with placed resources, instead of letting the GPU decide where to place each resource, and potentially run into VRAM fragmentation in the long run? Or will the driver perform heap defragmentation?
CreateCommittedResource creates an implicit heap each time it is called, while CreatePlacedResource simply creates the resource over the memory I choose on an existing heap, and is therefore much faster. Wouldn't it be preferable in most cases to use placed resources instead? Especially if I am interested in creating loading screens that don't miss a single frame deadline?

I am quite surprised to read from NVIDIA that committed resources are preferable to placed resources. Could anybody explain in more detail what else is happening under the hood, so committed resources are preferable to placed resources?


texts: How to avoid Gimbal Lock on Rubik's Cube

texts:
I am making a Rubik's cube program. That will simulate a Rubik's cube. I am having problems with gimbal lock. I need to know how to avoid it. To my understanding I can either multiply the x, y, z rotation matrices in a specific order to acquire the rotation I am trying to get. Or I can use a quaternion which is like rotating around a single user defined axis instead of the axis x, y, or z. I can't really understand visually how I can get the resulting axis from two other axis. (x, y, z) How can I get the resulting axis for my quaternion from my Euler rotations? Will it just result in gimbal lock again?

One of the big problems is. I don't know what rotations are going to be made. I need to make it general purpose.

Edit:
Little bit more documentation of my problem:

My Euler matrix multiplication looks like this

    rotate = XMMatrixRotationX(content.mesh[meshToRotate[i]].rotation.x) * XMMatrixRotationY(content.mesh[meshToRotate[i]].rotation.y) * XMMatrixRotationZ(radians);
    content.mesh[meshToRotate[i]].rotation.z = radians;

As a gimbal lock would suggest the last axis in the rotation gets the problem. When you attempt to rotate the front or back face you get problems.


texts: Why game window automatically scale itself when I press play?

texts:
When I am in the editor and I press play to test my game something weird happens,
the game window is like zooming in.. and I am not touching anything, the scale slider just goes from x0.41 to x1.
What may cause the problem? Bug in the editor?

Thank you in advance.

PS:
I noticed that the problem is only with my custom game windows, their initial scale is 0.41 and not 1, why is that?


texts: Calculate normals given vertices and indices

texts:
Can I calculate normals given vertices and indices? Can't figure out the code. Any help appreciated.

Edit: Could be it as simple as?:

function calculateVertexNormal(vertices:Array<Vector3>) {
        var vertNormal:Array<Vector3> = [];

        for(i in 0...vertices.length){
            var v0 = vertices[i];
            vertNormal.push(new Vector3(v0.x, v0.y, v0.z).normalized());
        }
        return vertNormal;
    }

Edit 2: Trying like this, with no luck

function calculateVertexNormal(vertices:Array<Vector3>) {
        var i = 0;

        while(i<indices.length){
            var A = vertices[indices[i]];
            var B = vertices[indices[i+1]];
            var C = vertices[indices[i+2]];

            var v1 = new Vec3().subvecs(A,B);
            var v2 = new Vec3().subvecs(A,C);
            var norm = new Vec3().crossvecs(v1, v2);

            normals.push(norm.x);
            normals.push(norm.y);
            normals.push(norm.z);

            i+=3;
        }
    }


texts:
I'm messing around with writing a really poor tactical RPG in C++. So far I have a 2D tile map and just got the A* algorithm working based on the pseudocode in the wikipedia.

But real tactical RPGs don't just find the best path on a flat plane and move there. They typically have limited move ranges and must climb up or down. If you've ever played Final Fantasy Tactics these would be affected by the Move and Jump stats. This is where I get lost. How do I alter the A* algorithm so that it finds the best path toward a target, but the path is only so many tiles long? How should I take height differences and jump stats into account? How do I implement jumping over a gap?

If it helps, right now my map is represented by a Vector of Tile objects. Each tile has pointers to the North, South, East, and West tile, which are set to a nullptr if no tile exists there, such as along the edge of the map or if a tile is set to non-passable.


texts: Help me Make Sense of Unity 2D Resolution Management

texts:
I am trying to set up an environment for a retro style pixel art game in Unity 2D. I aim for a vertical resolution of 240 pixels, and then, I would like the horizontal resolution to be dependent on the target screen's aspect ratio, so, on a 4:3 screen 320x240, on 16:9 around ˜432x240, and so on.
I have read a bunch of tutorials, added pixel perfect to my main camera, set up a target resolution in player preferences, set the pixel in a unit to 8 pixels everywhere, but still cannot make heads or tails of how it actually works.
Here is an image of my scene with my camera selected:

If I am correct, the dashed line of the camera is my target resolution, although it is weird as the green image I used as a background has a native resolution of 216 pixel vertical, yet it fills up the supposedly 240 pixel high camera. I have no idea what the solid green line is, and don't even get me started of the canvas, whose render target is set for camera yet it is obviously many times bigger than that.
Can someone please explain it to me how to properly set up a 2D environment described in my opening, point out my mistakes, point me to a good tutorial, or just give me advice on how to understand Unity's resolution management?


texts:
i am currently in the process of implementing a render engine that works like flash's. Where a sprite is drawn inside another sprite and reflects all transformation (rotation, scale, etc) on the parent.

I have my transformation setup like so.

    public Matrix transform
    {
        get
        {
            Matrix m_transform =
                Matrix.CreateTranslation(new Vector3(x, y, z)) *
                Matrix.CreateRotationZ(rotation) *
                Matrix.CreateScale(scale)
                ;
            return m_transform;
        }

    }

But i cannot use spritebatch to render the sprite with a matrix. Is there a way to properly do this ?

Thanks alot ;)


texts: How can I stop the ball from bouncing forever without changing the gravity?

texts:
I am using Monogame in Visual Studio 2019 and I need to find a method to make the ball that I fired with the cannon stop after bouncing from the ground, and while doing this, I have to not change the gravity.

gravity = 10;
yFriction = 0.2;

    public override void Update(GameTime gameTime)
    {
        position += velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;

        velocity.Y += gravity;

    }
    public void CheckBounce(SpriteGameObject other)
    {
        if (!this.CollidesWith(other)) return;

        CollisionResult side = this.CollisionSide(other);
        Bounce(side);

        // Relocating the ball if it's in the wall
        switch (side)
        {
            case CollisionResult.LEFT:
                position.X = other.Position.X + other.Width + this.Center.X;
                break;
            case CollisionResult.RIGHT:
                position.X = other.Position.X - this.Center.X;
                break;
            case CollisionResult.TOP:
                position.Y = other.Position.Y + other.Height + this.Center.Y;
                break;
            case CollisionResult.BOTTOM:
                position.Y = other.Position.Y - this.Center.Y;
                break;
        }
    }

    public void Bounce(CollisionResult side)
    {
        switch (side)
        {
            case CollisionResult.BOTTOM:
                velocity.Y *= yFriction;
                Stop();
                velocity.Y *= -1;
                break;
            case CollisionResult.TOP:
                velocity.Y = Math.Abs(velocity.Y) * yFriction;
                break;
            case CollisionResult.LEFT:
                velocity.X = Math.Abs(velocity.X) * xFriction;
                break;
            case CollisionResult.RIGHT:
                velocity.X = Math.Abs(velocity.X) * -xFriction;
                break;
        }
    }
    public void Stop()
    {
        if (velocity.Y <= gravity)
        {
            velocity.Y -= velocity.Y;
        }
    }

At this moment it puts it's velocity.Y to 0. But the problem is the gravity. After bouncing because it doesn't collides, it keeps adding velocity to the ball. As a result I printed out this variables:
After gravity adding
39.01105
After gravity adding
49.01105
After Friction
9.80221
After Stop
0
After bounce
0
After gravity adding
10
After gravity adding
20
After gravity adding
30
After gravity adding
40
After Friction
8
After Stop
0
After bounce
0
After gravity adding
10
After gravity adding
20
After gravity adding
30
After gravity adding
40
After Friction
8
After Stop
0

And keeps so on.
Thank you all in advance.


texts:
I'm working on an Ogre3D + Bullet project that involves planets in a solar system. For all intents and purposes, I'm looking to give each planet it's own gravity sphere.

So far, all I've found are ways to change the "general" gravity Vector3 for the entire scene, but that's it.

While I'd hope to add air friction and other physics later on, for now I just want "prioritized" gravity, like in this video.

You'll note that the floor in the video has gravity, but when he jumps near the sphere, he is attracted to it sphere instead. That's exactly what I'm going for.

The video is very low quality and doesn't explain how any of it is working, besides the fact that it uses Ogre3D and Bullet.

The planets themselves are on pre-generated paths around the Sun - I'm not looking to apply "real" physics to the solar system itself; just for the planets themselves and eventually "generated gravity" for ships in space.


texts: Is game localization by external files protected by a patent?

texts:
http://www.google.ch/patents/US7930167

This patent explains loading game languages from external files. I'm pretty sure that has already been implemented in many games. I'm not sure if they violate the patent or not. What kind of localization would be allowed then?


texts: What's wrong with using a static class to load and expose all of my assets?

texts:
What are the pitfalls associated with loading and storing all references to all of your content/assets within a single static class?

I've been trying to ask myself why I would want to instantiate an assets bank and can not think of a good reason to do so.

I have made a static class which enumerates through my game assets and adds each one to a dictionary which I can access (safely exposed, of course) anywhere like so:

var tex = Assets.Image("folder\\easyaspie");
spriteBatch.DrawString(Assets.Font("font2"), new Vector2(100, 100), Color.White);

... you get the picture.

I appreciate that this gets much more complicated when you have so many assets that having them all loaded at once is not a good idea. However, there is nothing to stop you from including selective loading of assets in your static class, as well as having static methods to change the contents of the 'reference banks'.

What do you think?

Edit:

My examples are pretty shallow, I recognise it's not a good idea to attempt to grab the reference of an asset mid-draw and is much better stored locally.


texts: Finding the closest point on a concave mesh (Unity C#)

texts:
One of my game systems requires that I find the closest point on a generalized mesh, which more often than not will be concave. This prevents me from just using Unity's built in ClosestPoint function, and all other alternatives have some other caveat which prevents me from using them so far.

The meshes are dynamically generated, pretty complex, and altered often, so it would be computationally unreasonable to split it into multiple convex meshes, unless there's some way I don't know about which allows fast splitting/reattachment of said meshes.

I considered checking a sphere around the point, and increasing the size of that sphere until I get a collision, but OverlapSphere and CheckSphere don't give any means to check the point of collision, only to check whether there was a collision at all.

Continuing with that train of thought, I tried a Spherecast with the same method and the maximum distance set to zero, but that didn't work either. Spherecasts don't detect any objects which are inside of the starting sphere location, so setting the distance to zero will result in no collision every time.

As a workaround to that, I tried setting the distance to a small positive number, equal to the step size which the Spherecast increases by each pass (in my case, 0.2). This almost works, but causes the cast to only detect collision points if I have a general direction to give it. There are two ways I tried to resolve this:

The first is by just passing in the direction from the point towards the center of the mesh I am trying to find collisions with, and although this works for a sphere, it breaks down for most of my other test cases, and just in a lot of different scenarios (Very concave polyhedra and shapes such as torii being two examples of situations where this method does not work.)

The second method I tried was to just take the direction to the closest point on the last frame, and pass that into the Spherecast. Again, works in some situations, but breaks down on large dihedral angles. Neither of these are really sufficient for what I need them for.

In terms of the constraints which I have to work under, the point should always be on the outside of the mesh, and the point should never be too far away from the mesh, but other than that there isn't really much else I can guarantee. Both the shape and the topology of the mesh are subject to change over time.

Any help would be greatly appreciated, thanks in advance!


texts: Direct3D11 HLSL ConstantBuffer Driver Stopped Responding

texts:
I have a simple HLSL shader with a few constant buffers, 1 of them holding an array of Light structs which causes my display driver to crash when the array size goes over 3.

Does anybody have an idea what causes my display driver to crash when MAX_LIGHTS is higher than 3? I don't believe I am exceeding the maximum allowed number of elements right? Which is supposed to be somewhere near 4096 elements). I also don't think I have set up my constant buffer wrong. It is a multiple of 16.

(I have excluded the other 3 constant buffers because these are not so interesting. They only contain world/view/proj matrices.)

I don't mind posting more code, if required.

#define MAX_LIGHTS 4 // Black Geometry / Crash
//#define MAX_LIGHTS 3 // Properly Shaded & Textured Geometry / No Crash

struct Light {

    // 16
    float4 lightPosition;

    // 32
    float4 lightDirection;

    // 48
    float4 lightColor;

    // 52
    float lightRange;

    // 56
    float lightIntensity;

    // 60
    float lightIsEnabled;

    // 64
    uint lightType;
};

cbuffer CBLights : register(b3) {
    Light lights[MAX_LIGHTS];
    uint numLights;
    float cbLightsPadding1;
    float cbLightsPadding2;
    float cbLightsPadding3;
};


texts:
How to calculate a child UI image's anchoredPosition(?) based on screen position input?
I'm trying to have the child UI image (Spotlight) show up where the eyeball UI is, but it seems to always be offset. The eyeball correctly shows up based on the Screen Position.

It is perfect when the Canvas is at 1080x1920 (set to scale)
But when I try it using others screen resolutions such as 1125x2436, the issue above shows up.
None of these attempts work. The gif is based on the one not commented out here:
p=Input.mousePosition; // screenPosition

    public static void SetRTPos(Transform g,Vector2 p,Canvas c)
    {
        RectTransform rt = g.GetComponent<RectTransform>();
        rt.anchorMin = Vector2.zero;rt.anchorMax = Vector2.zero;
        rt.pivot = Vector2.zero;
        // rt.anchoredPosition = RectTransformUtility.PixelAdjustPoint(p,g.parent,c);
        //rt.anchoredPosition = new Vector2(p.x* (float)c.pixelRect.x, p.y*(float)c.pixelRect.y);//  c.scaleFactor;
        rt.anchoredPosition = new Vector2(p.x*1080f/Screen.width,p.y*1920f/Screen.height );
        //rt.localPosition = RectTransformUtility.ScreenPointToLocalPointInRectangle(rt.parent.GetComponent<RectTransform>(),p,Camera.main,out p2)
   }

The UI RectTransform for rt.parent:

The UI RectTransform for g (not the x,y,z are updated at runtime):


texts: How to create a magic orb like in Skyrim?

texts:
How would I go about creating magic orb that looks like from magic menu in Skyrim in Unity3D?

Here is what I have in mind: Orb Image

And a video of that effect from 0:09-0:13: Orb Video


texts: Confusion on HLSL Samplers. Can I Set Samplers Inside Functions?

texts: I'm trying to create a system where I can instance a quad to the screen, however I've run into a problem. Like I said, I'm trying to instance the quad, so I'm trying to use the same geometry several times, and I'm trying to do it in one draw call. The issue is, I want some quads to use different textures, but I  can't figure out how to get the data into a sampler so I can use it in the pixel shader. I figured that since we can simply pass in the 4 bytes of our IDirect3DTexture9* to set the global texture, I can do so when passing in my dynamic buffer. (Which also stores each objects world matrix and UV data) Now that I'm sending the data, I can't figure how to get it into the sampler, and I really want to assume that it's simply not possible. Is there any way I could achieve this?


texts:
I'm currently planing a game idea, a coop crew based space shooter, where the focus is set heavily on the coop part. Depending what role you have, complexity varies: Gunners and Pilots are pretty easy, while engineers and doctors are way more complex. Crews may contain two to maybe 8 people.

This is only an example for a coop game, while there are many others out there.

But my thinking was, what about the people that want to play alone? Or in less big crews on bigger ships.

As I said, there are many other games out there that try to solve that problem. Lovers in a difficult space time has an A.I. that is basically a commendable token, Guns of Icarus has simple A.I. dudes, while Endless Dungeon let's you play all of your characters RTS style.

In my case, writing an A.I. that does everything is problematic. Gunner and Pilot would be possible, but Engineer is to complex. And making the A.I. simply perfect could and would break the gameplay. Making them less reliable would force me to implement some sort of crew management just for Single-player. Doable but not the focus.

My question is: What other options for a coop game are there to make it playable and enjoyable for Single-player?

I'm looking for answers not just fitting for my game, but coop games in general.


texts:
I have created a strategy game where the units use Unity's NavAgent pathfinding and flocking algorithms.  This works well.  However, I need to add queueing so that units will queue sensibly.  This works most of the time, but it isn't perfect and I want to know if there's a better way of doing it.

My first draft was to simply check which unit is closest to the destination, but this caused issues because a group might be navigating around an obstacle and the unit closest is at the back of the queue... so the whole group stops.

Second draft checked the distance to destination based upon the length of the path each unit had to take.  This works far more often, but sometimes still has issues.  Sometimes the same problem happens, but much less often.  The one who is supposed to be moving stops, and so the entire group stops.

There's also a problem I've noticed, where the waiting units could sometimes benefit from rotating, even if they shouldn't be moving.  Unfortunately they sometimes get stuck and will wait before they can move, to rotate.  If they could rotate when forbidden from moving it'd help considerably too.

What I need to know...

How can I make Unity NavAgent's queue, so that they will wait for the other agents closest to the destination to move first?
How can I ensure that this does not stop agents from rotating while in a queue (rotating may move them into a better position in the queue).

Code:

Unit Movement Function

private void Movement()
{
    // Unit is moving.
    if (moveVectors.Count > 0)
    {
        navAgent.isStopped = false;

        // Check for whether to wait in queue.
        Vector3 nextVector = transform.position;
                nextVector += transform.forward * speed * Time.deltaTime;

        foreach (Unit unit in list)
        {
            if (unit != this &&
                unit.moveVectors.Count > 0 &&
                Vector3.Distance(unit.transform.position, nextVector) <= (unit.footprint + footprint) &&
                PathDistance(unit) < PathDistance(this))
            {
                navAgent.isStopped = true;
                return;
            }
        }
    }
}

There's a bit more to Movement, but it's not relevant so we'll ignore it for now.

PathDistance Function

private float PathDistance(Unit unit)
{
    Vector3 startPosition = unit.transform.position;
    Vector3 endPosition = unit.moveVector;
    Vector3 lastPosition = startPosition;
    Vector3[] path = unit.navAgent.path.corners;
    float distance = 0;

    for (int i = 0; i < path.Length; i++)
    {
        distance += Vector3.Distance(lastPosition, path[i]);
        lastPosition = path[i];
    }

    distance += Vector3.Distance(lastPosition, endPosition);
    return distance;
}

Is there a better way of achieving the result I want?


texts: Recommend a way to draw thousands of particles (liquid) per frame in Unity3d

texts:
I'm writing a plugin for this library for Unity3d.
I have it working and now I am looking for an efficient way to draw the particles.
My 1st test just uses sprites and runs fine on my laptop but I doubt it will be so good on a mobile device.

Is there a cheap way of simply drawing lots of particles to the screen each frame?
The library generates an array of all the particle positions which updates in FixedUpdate() so I can just draw everything in that array each frame.

I'm thinking maybe somehting in the Graphics namespace would handy here, like maybe Graphics.DrawTexture

Also I might consider doing some kind of metaballs like pass over the particles to make them look more liquid like.


texts:
I found something I can't understand.
I'm only a beginner, so I thought I could use the CarController Scripts of the Car Demo for making a little driving game with different models.

I wonder why the colliders are sub-objects and the RigidBody has "Gravity-Enabled" without falling apart.

my model falls apart with the same configuration.


texts:
Why do Monsters drop things in so many games?
It creates all sorts of problems, including:

in-game gold hyper-inflation

questionable moral implications, if there is a strong incentive toward killing things but no incentive not to

Monster-killing giving XP is equally bad - you rename an ingame currency to XP, the mechanics stay the same. Here you have something like "fighting force inflation," so after some levels you have to have giant giants attacking your small figure or it stops being interesting. This is just hyper-inflation written a different way.
Is it enough reward if a monster stops killing you?
What benefits of monster-killing rewards make up for these problems, or how can we compensate for those problems?


texts: Why do I get this weird shadow render error?

texts:
Using Unity 2018.2.14/15 I've recently been working on a small project and I encountered a very weird problem. It's hard to describe so here is a picture:

Originally I assumed it may be an issue with my shadow/lighting settings (I think it looks like that a lot), but I couldn't find any setting that had a direct impact on the lines.

Ignoring it sadly isn't an option and I don't know of any workaround...

Some additional information:

The problems are 2-3 well visible decreases in lighting brightness. It seems a bit like there is something causing automatically descending lighting quality the further away from the camera the walls are, however I haven't found a setting to change this yet.
Currently I'm using quads and a custom material based on the Standard Opaque Shader with an Albedo setup. I'm using a self-made Texture for the walls (and a normal map created from a grayscale/bumpmap version of the texture). However, I've also tried changing between all non-round Unity Standard Models with no result.
The lines are indeed dependent on Camera Distance (both Editor and ingame Camera). If I move the walls, the lines stay at the same position on the walls (like on a certain spherical radius around the camera). If I move the camera (editor and ingame camera display different lines) the lines move together with it.

Do you have any idea what's going on/what I can do to prevent those lines from appearing?

Thank you in advance! :)


texts:
How do I change the scene like you do on common android home screens?

I know i could detect if the player swipes to the right and then change the scene but this would not look as smooth as android home screens.


texts:
I'm working on a game which requires me to draw a few lines from a single point that is more formally said

Given point A with coordinates x,y I draw n lines where the i-th line has the coordinates named as xi,yi. Given the LineRenderer capabilities inside Unity3D I was unable to draw more than one line from a particular point with it since it renders only polylines.

I'm currently using the Debug.DrawLine() method which successfully renders the line. I have tried using GL.Begin() as it is shown in the Unity example but I cannot see my lines being drawn.

My question is : are there any other methods for doing this? If not, can you tell me how can I show the line that is being drawn with Debug.DrawLine() inside play mode? I've saw that I could use Gizmos.DrawLine() but I didn't quite understand it's usage.


texts: OpenGL ES 2.0: Repository of Quality Shaders

texts:
Could I kindly ask, to suggest me a repository of high quality OpenGL (OpenGL ES 2.0) vertex and fragment shaders, please?

I am looking for pixel based ligting shaders (such as phong) and simmilar. It would be nice to see more of them, to be able to choose between quality vs shader performance.


texts: Engine for 2D Top-Down Physics-Based Skeletal Animation

texts:
I just watched at the Sui Generis video, and was completely amazed. Specifically, the part where the big troll thing is beating up the player with his flail.

This got me really excited, and I would like to try implementing something like this in a 2D Top-Down format. Something like this.

That atloria example seems simple enough, but it's not exactly what I'm looking to make. I think atloria is using predefined animations, where as I would like to make something more physics-based like the Sui Generis engine does.

So, I'm wondering what physics engines might work for something like this, and if I'd need to implement my own skeletal system, or if I could just use "joints" and such from the engine. The only experience I have in terms of physics engines is Box2D, which I've heard shouldn't be used for top-down settings, and I can think of a few reasons it wouldn't work out well. One of those reasons being gravity. In box 2D, gravity pulls towards a side of the screen (usually the bottom.) I wouldn't want my player's forearms constantly being pulled to one side. :)

Also should mention that the programming language doesn't matter all that much to me. I'm currently playing with HTML5 stuff, though. :)

Thanks in advance!


texts:
I am trying to build simple game and I just bumped on some logical problem that I am sure many of you already came across. I have a plane - floor and several sprites-trees that have tree texture on them. It basically looks like this:
What I would like to do is to add dynamic shadows below the trees. I don't want to generate the shadows in runtime - I have texture for that. By "dynamic" I mean that I can control shadow length and rotation (simulating different times of day). And here I would like to ask you for best practice for that. I was thinking about adding small plane under each tree and control it's rotation and scaling directly from the game. The other idea I had was to use vertex shader to position, scale and rotate those planes. I was also thinking about using pixel shader to combine floor texture with shadow texture. The last idea has this advantage over the others that my floor may eventually be not flat, and the shadows would still be nicely casted. Also this would allow me to have shadows close to edges of the floor (which hangs in "space") and the shadows would not stick out from the floor. I would be grateful if you could suggest me some approach to the problem.


texts:
I have imported a new texture into UE, and have created a new sprite. I have setup the material of the sprite as follows:

I have also set my texture as texture-parameter. But my sprite renders brighter than its texture:

Why? What am I doing wrong?

Thank you in advance.


texts:
I've been working with XAudio2. After looking at the samples, example code, and sparse documentation available from Microsoft and the MSDN, I've found that there aren't any easy-to-find resources on creating and using XAPO effects, nor any XAPO effects produced by third parties that I can download and/or buy.

What it looks like is that if I create an app that uses XAPO effects, I'll have to create them all myself because there's no community of existing applications like there is with technologies like Apple's AU or Steinberg's VST. Is this true, or are there others using XAudio2 and XAPO and I just haven't found them?

Is there a place to ask programmer-support-related questions about XAudio2 and related technologies (or is this the best destination)? The best I've found so far are the XNA forums, which are game-specific and sparsely populated in the audio area.


texts: Troubleshooting Unity & Unity Hub Problems Behind Firewall

texts:
I'm teaching game design at a high school in the US. This means that we're behind a firewall that does packet inspection. Our lab machines are running Windows 10 and have the school's certificate installed as a "Trusted Root Certification Authority" (as seen in certlm).

The problem I'm seeing are:

Unity Hub (2.0.0) silently fails when trying to download Unity installs
Unity (2019.1.3f1) complains about a "self-signed certificate in the trust chain" (roughly)

This post from the Unity Forums suggests that Unity might know how to read the local computer's list of trusted certificates, but there are also responses indicating that it may not always work.

My questions:

Where do Unity and Unity Hub log certificate errors (do they)?
Suggestions for troubleshooting?


texts: Can I Create A Windows Package to Submit to the Window Store using the Mac Version of Unity 5.3?

texts:
Note: New to App Development.

I'm using a Mac for building my three 3D puzzle apps with Unity 5.3.2. I want to create Windows versions to sell in the Windows Store. I attempted to transfer the package for one of our apps to the Windows version of Unity but it was a pure hot mess. A lot of the alignment of text and images was skewed really bad. We have not used Windows in approx. 10 years so for all practical purposes we are brand new Windows users. The last OS we used was XP. The laptop we just purchased runs Windows 10 Home.

I can create a Windows executable (.exe) file from the Mac version of Unity that executes my 3D puzzle app perfectly just like the Mac version. However I found out that I had to submit a special package to the Windows Store. The instructions that I found so far for this assumes that you are using the Windows version of Unity.

I do not plan to be a full time app developer so the idea of trying to learn Visual Studio for me is a waste of my time. I would prefer creating the Windows package for the Windows Store using the Mac version of Unity. Is this possible? I could not find instructions in the manual or from search on what options need to be set to do this. I'm thinking it can be done since I was able to create a Windows exe file using my Mac version of Unity. I would like to create Windows Store packages for both 8.1 and 10.


texts: Accessibility of games, how is important for you?

texts:
I'm blind and I would know if there is someone that consider important the accessibility, from a blind in particular, when develop a new game.
I don't speak about an audio game, I'm speaking about a video game that implements a TTS or a GUI compatible with screen readers!


texts: SAT, How Do I Find The Penetration Vector?

texts:
I've just successfully implemented Separating Axis Theorem (SAT) in my game but I was wondering how do I find the penetration vector? I heard it can be useful for collision response. e.g. The harder they collide the harder the response.

I want the penetration vector so I apply it to the position of an object when it is current penetrating an other so I can move it back outside of the other object's bounds.

Here is my code so far.

Any help would be much appreciated,

Thanks in advance.


texts:
I've been following some tutorials about libGdx and I've tried to create a 2d platformer but I've got stuck at how would be the right way to make the camera not go out of the screen when the player moves :(
The camera follows the player when it moves on the x coordinate position but if i go near where the map ends the camera will go out of the screen  and i'm not sure how to solve that

Here is the main code of the game:

public PlayScreen(SuperShooter game){
        this.game = game;
        atlas = new TextureAtlas("Diz_Pack.atlas");
        gamecam = new OrthographicCamera();
        gamePort = new StretchViewport(SuperShooter.V_WIDTH / SuperShooter.PPM, SuperShooter.V_HEIGHT / SuperShooter.PPM, gamecam);

        hud = new Hud(game.batch);
        mapLoader = new TmxMapLoader();
        map = mapLoader.load("Level1WithObjects2.tmx");
        renderer = new OrthogonalTiledMapRenderer(map, 1/SuperShooter.PPM);
        //initailly set our gamecam to be centered correctly at the start of
        gamecam.position.set(gamePort.getWorldWidth()/2 , gamePort.getWorldHeight()/2, 0);

        world = new World(new Vector2(0,-10), true);

        new B2WorldCreator(world, map);

        controller = new Controller(game);

        // b2dr = new Box2DDebugRenderer();
        player = new John(world, this);

        world.setContactListener(new WorldContactListener());

    }

public void update(float dt){
        handleInput(dt);
        world.step(1/60f, 6, 2); // in order for box2d to execute our physics simulation we need to tell it how many times to calculate per second
        player.update(dt);
        gamecam.position.x = player.b2body.getPosition().x;
        gamecam.update();
        renderer.setView(gamecam);
    }

public void render(float delta) {

        update(delta);
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        renderer.render();
        //render our Box2dDebugLines
        //b2dr.render(world, gamecam.combined);

        game.batch.setProjectionMatrix(gamecam.combined);
        game.batch.begin();
        player.draw(game.batch);
        game.batch.end();

        game.batch.setProjectionMatrix(hud.stage.getCamera().combined);  //you have something that can draw to the screen via gpu like the spritebatch. And you have a camera.
        //you gotta tell the spritebatch where we are / where the camera is looking, because on screen shall be what the camera is looking at.
        hud.stage.draw();
        controller.draw();

    }

The camera is at first set on the left bottom of the screen but then, while the game updates it's placed on the x position of the player and that's why it looks like that:( do you guys know how should it be done to show only the map when the player moves? should i position the camera in front of the player or something like that?

Help would be appreciated! thanks


texts:
I am making a game in Blitz3d and I made simple gravity, however once the object falls on the ground, it goes through it very slowly. The ground is a plane and I have collision on it.

This is a pretty old engine, and not a lot of people are using it but I decided to use it because it's easier than Unity3D for me and it's very basic and customizable.

Here's my code:

AppTitle "FPS"
Graphics3D 800,600,32,2
SetBuffer BackBuffer()
SeedRnd MilliSecs()
HidePointer

;Objects
Global player = CreatePivot()
Global camera = CreateCamera(player)
Global cube = CreateCube()
Global light = CreateLight()
Global plane = CreatePlane()
Global cube2 = CreateCube(player)
col_plane = 1
col_player = 2
col_cube = 3

;Vars
gravity# = -.00001
plx# = 0
ply# = 0
plz# = 0
pldx# = 0
pldy# = 0
pldz# = 0

;Textures
CameraClsColor camera,135,206,250
box = LoadTexture("models\box.png")
dirt = LoadTexture("models\dirt.jpg")

;Object Details
EntityType cube,col_cube
EntityType player,col_player
EntityType plane,col_plane
EntityRadius player,1.2
EntityRadius plane,1

PositionEntity player,0,10,5
PositionEntity cube,0,1,5
PositionEntity light,0,2,0
PositionEntity plane,0,0,0
EntityTexture cube,box
EntityTexture plane,dirt
ScaleTexture dirt,5,5
CameraRange camera,0.25,200

;Called Functions
While Not KeyHit(1)
    Cls
    ;Collisions
    Collisions col_player,col_plane,2,2
    Collisions col_player,col_cube,2,2

    If ply < -2 Then
        ply = 0
        pldy = -pldy*.39
    EndIf
    If ply < -1.8 Then
        pldx = .6*pldx
        pldz = .6*pldz
        If KeyDown(57) Then pldy = 2
    EndIf
    pldy = pldy + gravity
    plx = plx + pldx
    ply = ply + pldy
    plz = plz + pldz
    PositionEntity player,EntityX(player)+plx,EntityY(player)+ply,EntityZ(player)+plz

    control()
    RenderWorld()
    UpdateWorld()
    MoveMouse GraphicsWidth()/2, GraphicsHeight()/2
    Flip
Wend

End

;Functions
Function control()
    If KeyDown(42) ;Shift (for running)
        If KeyDown(17) And KeyDown(30) ;W and A
            MoveEntity player,-0.15,0,0.15
        ElseIf KeyDown(17) And KeyDown(32) ;W and D
            MoveEntity player,0.15,0,0.15
        ElseIf KeyDown(17) And KeyDown(30) ;S and A
            MoveEntity player,-0.15,0,-0.15
        ElseIf KeyDown(17) And KeyDown(32) ;S and D
            MoveEntity player,0.15,0,-0.15
        ElseIf KeyDown(17) ;W
            MoveEntity player,0,0,0.15
        ElseIf KeyDown(31) ;S
            MoveEntity player,0,0,-0.15
        ElseIf KeyDown(30) ;A
            MoveEntity player,-0.15,0,0
        ElseIf KeyDown(32) ;D
            MoveEntity player,0.15,0,0
        End If
    Else ;Walking
        If KeyDown(17) And KeyDown(30) ;W and A
            MoveEntity player,-0.1,0,0.1
        ElseIf KeyDown(17) And KeyDown(32) ;W and D
            MoveEntity player,0.1,0,0.1
        ElseIf KeyDown(17) And KeyDown(30) ;S and A
            MoveEntity player,-0.1,0,-0.1
        ElseIf KeyDown(17) And KeyDown(32) ;S and D
            MoveEntity player,0.1,0,-0.1
        ElseIf KeyDown(17) ;W
            MoveEntity player,0,0,0.1
        ElseIf KeyDown(31) ;S
            MoveEntity player,0,0,-0.1
        ElseIf KeyDown(30) ;A
            MoveEntity player,-0.1,0,0
        ElseIf KeyDown(32) ;D
            MoveEntity player,0.1,0,0
        End If
    End If

    While KeyDown(16) ;Q
        RotateEntity camera,MouseXSpeed(),10,10
    Wend
    While KeyDown(18) ;E
        RotateEntity camera,0,-10,-10
    Wend

    TurnEntity player, 0, -MouseXSpeed()/6.0, 0
    TurnEntity camera, MouseYSpeed()/6.0, 0, 0
    If EntityPitch(camera) < -70
        RotateEntity camera, -70, EntityYaw(camera), EntityRoll(camera)
    ElseIf EntityPitch(camera) > 70
        RotateEntity camera, 70, EntityYaw(camera), EntityRoll(camera)
    EndIf
End Function

If there's some one who can actually help me with this, I would appreciate it.


texts:
So I have this game and I would like to have a save function. Here is my code below:

function SaveData() {
  localStorage.setItem('save', score);
  localStorage.setItem('save', btoa(JSON.stringify(score)));
}
function LoadData() {
  score = window.localStorage.getItem('save');
  document.getElementById('demo').innerHTML = score;
}
window.onload = function()  {
LoadData();
}

When it loads it does not use the storage or it says Not a Number (NaN)


texts: Google play services not working in unity

texts:
I've done everything as specified- Linked my app to play services in the developer console. Added the SHA1 from Applications -> Release Management -> App signing -> Upload certificate. Downloaded the latest 'play services' unity package from GitHub. Added the required 'resource' to the play services setup in unity editor. Added the following script to the 'Canvas' object:
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using GooglePlayGames;
 using GooglePlayGames.BasicApi;
 using UnityEngine.SocialPlatforms;

 public class PlayGamesServices : MonoBehaviour
 {
     // Start is called before the first frame update
     void Start()
     {
         PlayGamesClientConfiguration clientConig = new
         PlayGamesClientConfiguration.Builder().Build();
         PlayGamesPlatform.InitializeInstance(clientConig);
         PlayGamesPlatform.Activate();
         Social.localUser.Authenticate((bool success) =>
         {
             if (success)
                 Debug.Log("Logged In");
             else
                 Debug.Log("Failed to Log In");
         });
     }

     public static void PostToLederboard(long newHighScore)
     {

   Social.ReportScore(newHighScore,GPGSIds.leaderboard_global_high_score, (bool success) =>
         {
             if (success)
                 Debug.Log("New High Score posted");
             else
                 Debug.Log("Unable to post New High Score");
         });
     }

     public void ShowLeaderboard()
     {
    PlayGamesPlatform.Instance.ShowLeaderboardUI(GPGSIds.leaderboard_global_high_ score);
     }
 }

I've already published my game to alpha testing and then implemented play services. I'm wondering if that's the problem.
I've run the adb logcat and this error popped up:

[Play Games Plugin DLL] 07/21/19 12:06:19 +05:30 ERROR: UnityEngine.AndroidJavaException: java.lang.ClassNotFoundException: com.google.games.bridge.TokenFragment 07-21 12:06:19.325 23287 23314 W Unity :
at UnityEngine.AndroidJNISafe.CheckException () [0x00000] in <00000000000000000000000000000000>:0 07-21 12:06:19.325 23287 23314 W Unity :
at UnityEngine.AndroidJNISafe.CallStaticObjectMethod (System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) [0x00000] in <00000000000000000000000000000000>:0 07-21 12:06:19.325 23287 23314 W Unity :
at UnityEngine.AndroidJavaObject._CallStatic[ReturnType] (System.String methodName, System.Object[] args) [0x00000] in <00000000000000000000000000000000>:0 07-21 12:06:19.325 23287 23314 W Unity :
at UnityEngine.AndroidJavaClass._AndroidJavaClass (System.String className) [0x00000] in <00000000000000000000000000000000>:0 07-21 12:06:19.325 23287 23314 W Unity :
at GooglePlayGames.Android.AndroidTokenClient.DoFetchToken (System.Boolean silent, System.Action`1[T] callback) [0x00000] in <00000000000000000000000000000000>:0 07-21 12:06:19.325 23287 23314 W Unity :
at System.Action.Invoke () [0x00000] in <00000000000000000000000000000000>:0 07-21 12:06:19.325 23287 23314 W Unity :
at GooglePlayGames.OurUtils.PlayGamesHelpe

I've tried reproducing the error by re-doing the exact same steps in an empty project and ended up with the same error.

Update:
When i change Player Settings -> Publishing -> Minify ->
Release to None and Debug to None the error is gone and play services sign-in was successful.
This worked for the empty project, however when i make the same change in my original game project the build fails with errors.
How do I build my game without errors when Minify is set to None?


texts: Architecture design in "buff-heavy" game?

texts:
I've been trying to wrap my head around this architectural design problem. Think of a game that has lots of spells and buffs (World of Warcraft, Diablo II etc), i.e. spells may cause buffs on characters. Each buff may affect one or several properties. For example a frost bolt normally slows down the target it hits, but if it does a critical hit, it will freeze the target for a moment. The frost bolt will also cause cold damage. A shadow bolt might cause some kind of "black" damage and cause confusion (i.e. invert controls, randomize spell target etc).

I tried to map out the architecture for this kind of spell-buff system, but I'm having trouble connecting the dots. First I thought of entity-component system where each character would have a list of components (health, mana, input...), and each buff would "affect" all these components. The components would then choose whether or not the buff affects it. For example, a "damage-over-time" buff should affect the health component, but not the mana component. The aforementioned shadow bolt would affect both health and input components. However, this feels a bit iffy to do if there's tens or hundreds of buffs and components.

Any ideas on how to approach such a design?


texts: Unity3d: "random" transform position values on editor

texts:
Run into some strange behavior on editor position values.

https://youtu.be/DUBpbOUkbfo

As you can see we have two cube object with colliders on both and rigidbody on parent.
After start play mode parent object editor values sets to some random numbers while transform.localPosition and transform.position is still (0,0,0).

This somehow related to parent-child physics hierarchy but can't understand how.


texts: Instancing meshes messing up scene lighting

texts:
I've been rendering a scene (some objects over a large field of grass) to test shadow mapping which is working fine.

But when I use instancing to "gain" performance, I not only get a decrease in performance (by losing 2-4 ms per frame !), but my lighting also gets messed up.

Comparaison :

Scene without instancing :

Scene with instancing :

The shadows are still rendered fine, but the grass lighting is completely off, alternating between dark and bright grass. The small "scene" above the grass is also very dark (I use the same shader as the one for the grass, for convenience purposes).

Even the debug text in the upper left corner isn't being rendered anymore...

I use the same shader for both scenes, except I use a uniform to let the shader know when I use instancing and when I'm not.

Here is the lighting shader:

//Vertex Shader
#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec2 texCoords;
layout (location = 2) in vec3 normal;
layout (location = 3) in mat4 a_model;

out vec2 TexCoords;

out VS_OUT
{
    vec3 FragPos;
    vec3 Normal;
    vec2 TexCoords;
    vec4 FragPosLightSpace;
} vs_out;

uniform bool instanciate;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
uniform mat4 lightSpaceMatrix;

uniform float u_time;

void main()
{
    mat4 model1;
    if (instanciate)
        model1 = a_model;
    else
        model1 = model;
    //Grass movement
    float time = u_time + 8.5f * gl_InstanceID;
    vec3 pos = position;
    float fact = 7/position.y;
    float sx = sin(pos.x*32.0+time*4.0)/fact*0.5+0.5;
    float cy = cos(pos.y*32.0+time*4.0)/fact*0.5+0.5;
    vec3 displacement = vec3(sx, cy, sx*cy);
    vec3 normalN = normal.xyz*2.0 - 1.0;

    pos = pos + normalN*displacement*vec3(0.06, 0.06, 0.06)*vec3(8.0, 3.0, 1.0);

    gl_Position = projection * view * model1 * vec4(pos, 1.0f);
    //Used for shadow mapping
    vs_out.FragPos = vec3(model1 * vec4(position, 1.0));
    vs_out.Normal = transpose(inverse(mat3(model1))) * normal;
    vs_out.TexCoords = texCoords;
    vs_out.FragPosLightSpace = lightSpaceMatrix * vec4(vs_out.FragPos, 1.0);
}

The fragment shader didn't change when I implemented instancing, so I don't think it's relevant to put it here.

Also, here is how I render the scene :

    glUniform1i(glGetUniformLocation(programMesh, "instanciate"), GL_TRUE);
    //The buffer is setup before with the matrices
    glEnableVertexAttribArray(3);
    glBindBuffer(GL_ARRAY_BUFFER, modelbuffer); // model matrices buffer
    glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)0);
    glEnableVertexAttribArray(4);
    glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(vec4Size));
    glEnableVertexAttribArray(5);
    glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(2 * vec4Size));
    glEnableVertexAttribArray(6);
    glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(3 * vec4Size));

    glVertexAttribDivisor(3, 1);
    glVertexAttribDivisor(4, 1);
    glVertexAttribDivisor(5, 1);
    glVertexAttribDivisor(6, 1);

    double instanceTime = elapsedTIme;
    glUniform1f(u_time, instanceTime);
    glDrawArraysInstanced(GL_TRIANGLES, 0, vertices.size(), 100);

    glUniform1i(glGetUniformLocation(programMesh, "instanciate"), GL_FALSE);

I don't really know where the problem could be.

I can give more code if needed.

Thanks in advance for any help.


texts: Unity - Instantiate 2 copies at same time?? (Asteroids clone) C#

texts:
I haven't been at my computer learning code or game dev in a few months and am just starting again. I am trying to make a game very similar to Asteroids. In 3d but fixed camera from above so basically disregarding the Y Axis at the moment.

I have everything working fine so far such as the rocket stays in middle and can rotate, and fire weapon. The Asteroids for now all come from the top side of the screen, and have some code to randomise the X location and speeds.

When the laser hits the Asteroid I want it to destroy that Asteroid and create two more that are half the size and with a Rotation added of 45/-45 degrees.

I have the code that I thought would work but it is only creating one more and not two. (note: as you'll see I have tried making tempAsteroid2 and even asteroidPrefab2, before this I just had the one which I tried to instantiate twice).

What am I missing? why does this code not make two more appear upon laser collision??

Any help massively appreciated as always. Many thanks:

public class Asteroid : MonoBehaviour {
float speed;
public GameObject asteroidPrefab, asteroidPrefab2;
public int sizeKey = 2;
// Use this for initialization
void Start () {
    if (sizeKey < 1)
    {
        Destroy(this.gameObject);
    }
    transform.position.Set(transform.position.x, 0f, transform.position.y);
    speed = Random.Range(0.5f, 2f);
}

// Update is called once per frame
void Update () {
    GetComponent<Rigidbody>().transform.Translate(Vector3.forward * speed * Time.deltaTime);
}

private void OnTriggerEnter(Collider other)
{
    if (other.tag == "Laser")
    {
        BreakAsteroidInHalf();
        Destroy(other.gameObject);
    }
}

void BreakAsteroidInHalf()
{
    GameObject tempAsteroid = asteroidPrefab;
    tempAsteroid.transform.position = transform.position;
    tempAsteroid.transform.Rotate(0, -45, 0);
    tempAsteroid.transform.localScale *= 0.5f;
    tempAsteroid.GetComponent<Asteroid>().sizeKey -= 1;
    Instantiate(tempAsteroid);
    GameObject tempAsteroid2 = asteroidPrefab2;
    tempAsteroid2.transform.position = transform.position;
    tempAsteroid2.transform.Rotate(0, 45, 0);
    tempAsteroid2.transform.localScale *= 0.5f;
    tempAsteroid2.GetComponent<Asteroid>().sizeKey -= 1;
    Instantiate(tempAsteroid2);
    Destroy(this.gameObject);
    Debug.Log("Asteroid destroyed and replaced by 2 more");

}


texts:
I've followed this tutorial https://developers.google.com/admob/android/quick-start, but I'm stucked at gradle configuration. I've added line

compile 'com.google.android.gms:play-services-ads:8.3.0'

to build.gradle (of application) like in tutorial, but error "Failed to find: com.google.android.gms:play-services-ads:8.3.0" appeared. Admob writers says, that android studio will offer download if that is missing, but I've only got error in output.


texts: Ray casting through terrain mesh + Octree ( Mesh collision )

texts:
I'm currently in development of a terrain editor which i will use for my game. One thing that is partially stopping my development is that I don't have collision detection implemented between mouse ray cast and the terrain mesh.

The terrain is consisted of triangles and can be lowered and raised.Also the x and y values of the mesh don't change. Of course what i need to do is ray cast through my mouse positions and get intersected triangle. I would get the point on the triangle using Barycentric coordinates. Just I'm not quite sure how does octree come into play here. As far as I understand it it works like a 3d quadtree, splitting the box into smaller box that the ray intersects. But which box do i choose ? How do i know which box is the closest one to the terrain, if either raised or lowered terrain ? How many subdivisions would i have? I was thinking on having as much as i have tiles( basically the last level of subdivisions would correspond to a x^3 box).

Right now i'm just doing collision with the 0 Z-value plane, and it works okay, but if the terrain is a bit raised then this can give faulty results.

Other two methods that i found is to iterate through the mesh, which of course is insanely inefficient; the other is to project the terrain in reverse and then i guess do some checking with the mouse coordinates (think it's called z-buffer checking or something).

If anyone has any other ideas i'm all ears. Just note that the algorithm should be an efficient one (of course this depends on the implementation) and accurate.

Thanks !


texts:
I have two game objects named A and B, just as follows:

I want to move object B to this virtual line without any rotation so that the destination is B' . What I have are transformation of object A and B. I'm brand new to Unity3D and its APIs, so I don't know how should I get this done.


texts: Move object along world X/Z axes taking account it's own rotation

texts:
I have a camera 9 units up, tilted down at a 60° angle (rotated around it's X-Axis), which means forward for the camera is pointed down at the floor as shown in the picture below

Now when I press W, i want the camera to move horizontally forward without changing it's Y coordinate, but not along the world Z axis, as that breaks when the camera is rotated around it's Y axis. Here are a few images demonstrating what I want
Side view:

Top view:


texts: Pygame, how can I move a rect/sprite from point A to B smoothly?

texts:
As the title suggests, i want to move a rect/sprite from point A to point B in a smooth manner. What I mean more specifically is that the speed of the movement should change throughout the course. So it starts off slowly then speeds up as it reaches the half-way point then slows down again to finally land exactly on B. Or it can just start off fast then to slow down right till it hits B.

I've already tried to do this once by making the acceleration of the object 1/2 of the distance it needed to travel then halving the acceleration again before every frame. Then after a while it just reassigns the objects position to exactly where it needs to be. But i don't really like this method and i thought there had to be a more elegant and efficient way of doing it. But I can't think think of anything.

Here's what I've got so far(It's not the one that 1/2s acceleration):

clock = pygame.time.Clock()

class Block():
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y

        self.rect = pygame.rect.Rect((self.x, self.y, width, height))

    def draw(self, surface):
        pygame.draw.rect(screen, (55,150,55), self.rect)

        self.x = self.rect.left
        self.y = self.rect.top

    def move(self, vect):
        x = vect[0] - self.rect.left
        y = vect[1] - self.rect.top

        self.rect.move_ip(x, y)

block = Block(100, 100, 50, 50)

def gameloop():

    loopExit = True

    while loopExit == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loopExit = False
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_d:
                    block.move([5,0])

            if event.type == pygame.MOUSEBUTTONUP:
                block.move(pygame.mouse.get_pos())

        screen.fill((25,25,25))

        block.draw(screen)

        clock.tick(60)

        pygame.display.flip()

gameloop()


texts: Understanding the ways to access a Graphics object for drawing in Java

texts:
I'm making a game in java right now. I've looked around at various tutorials for making Java games and there doesn't seem to be a consistent way to access a Graphics object to draw stuff on the screen.

Three of the different ways have been

Overriding the paintComponent() method in a class that extends JPanel
Using the getGraphics() method to get the graphics object in a class that extends JPanel
Creating a BufferStrategy object and using the getDrawGraphics() method to get the graphics object to draw

All three implementations seem to work, I'm just confused about the difference between them, and in which situations would you use each?


texts:
I want to know is there a way of using Mathf.SmoothStep to control the float of a variable? You see I downloaded this package ("Frost Effect by Steven Craeynest") on Unity Asset Store and created a IEnumerator OnTriggerEnter2D (in a new script) to control the effect once my player hits an orb, making it slow down but now I want to add an animation. Rather than having it appear of the screen and then disappearing, I want to make the frost effect slowly come in, kinda like controlling the frost amount in the inspector. It is possible, because I tried doing it like this:

(This is attached to orb)

// Use this for initialization
void Start () {
}

IEnumerator OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") {
        //frost.enabled = true;
        GameObject.Find("Main Camera").GetComponent<FrostEffect>().enabled = true;
        FrostEffect.valToBeLerped = Mathf.SmoothStep(0, 1f, FrostEffect.FrostAmount);
        yield return new WaitForSeconds (1.01f);
        FrostEffect.valToBeLerped = Mathf.SmoothStep(1, 0, FrostEffect.FrostAmount);
        GameObject.Find("Main Camera").GetComponent<FrostEffect>().enabled = false;
    }
}

But it's still appearing automatically rather than it slowly coming in like an animation. Anyway this is the frost effect script I downloaded from the assets store:

(Attach to the main camera)

public static float FrostAmount = 0.3f; //0-1 (0=minimum Frost, 1=maximum frost)
public static float valToBeLerped = 0;
public float EdgeSharpness = 1; //>=1
public float minFrost = 0; //0-1
public float maxFrost = 1; //0-1
public float seethroughness = 0.2f; //blends between 2 ways of applying the frost effect: 0=normal blend mode, 1="overlay" blend mode
public float distortion = 0.1f; //how much the original image is distorted through the frost (value depends on normal map)
public Texture2D Frost; //RGBA
public Texture2D FrostNormals; //normalmap
public Shader Shader; //ImageBlendEffect.shader

private Material material;

private void Awake()
{
    material = new Material(Shader);
    material.SetTexture("_BlendTex", Frost);
    material.SetTexture("_BumpMap", FrostNormals);
}

private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    if (!Application.isPlaying)
    {
        material.SetTexture("_BlendTex", Frost);
        material.SetTexture("_BumpMap", FrostNormals);
        EdgeSharpness = Mathf.Max(1, EdgeSharpness);
    }
    material.SetFloat("_BlendAmount", Mathf.Clamp01(Mathf.Clamp01(FrostAmount) * (maxFrost - minFrost) + minFrost));
    material.SetFloat("_EdgeSharpness", EdgeSharpness);
    material.SetFloat("_SeeThroughness", seethroughness);
    material.SetFloat("_Distortion", distortion);
    ///Debug.Log("_Distortion: "+ distortion);

    Graphics.Blit(source, destination, material);
}

Thank you. :)

Second Edit
Because so far this is what I have:

        GameObject.Find("Main Camera").GetComponent<FrostEffect>().enabled = true;
        float duration = 2f;
        DOTween.To(x => FrostEffect.FrostAmount = x, 0.0f, 0.34f, duration)
            .OnComplete(()=>DOTween.To(x => FrostEffect.FrostAmount = x, 0.34f, 0.0f, duration));
        Time.timeScale = 0.05f;
        yield return new WaitForSeconds (6.5f);
        Time.timeScale = 1f;


texts: Access gameObject array value from other script

texts:
I'm trying to access gameobject array values from one script to another. I have attached certain gameobject capsules with the array in the editor as shown in the figure below and I'm trying to access the values of array to another script. But I get null values when i try to pass the values. I don't want to use gameobject tag since i have to set gameobject active and deactive during runtime.

PinsScript.cs

public class PinsScript : MonoBehaviour {

        // Use this for initialization
        public GameObject[] pins;
        void Start () {

        }

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

        }
}

MovingBall.cs

PinsScript p = GetComponent<PinsScript>();

        foreach (GameObject pin in p.pins)
        {

             pin.SetActive(false);

        }


texts: How to organize passing data to shaders in cross-API render system?

texts:
I try to create rendering system that supports DirectX and OpenGL. I am trying to create class for constant buffer, but DirectX constant buffers and OpenGL uniform buffers have different memory organisation rules.
Is there any way to to achieve the compatibility between DirectX and std140 from OpenGL?

Or probably will it be better to choose a other way to create abstraction of constant buffers for shaders? And how developers solve problem of passing data to shaders effectively in serious engines?


texts: What are some rarely-mentioned networking models/strategies?

texts:
I've been thinking about multiplayer and networking a lot lately, and I've found oodles of information, but I feel like there might be some standard models or strategies for networking that I haven't seen.

There's the obvious client-server model, using the client as a terminal that sends keystrokes and recieves location information about the other entities.
There's a point to point model, I believe - how two clients can play a game without the setup of a dedicated server (seen in LAN a lot).
There's the client prediction strategy where the client is allowed to take control of the player while it waits for latency to bring back the server's actual position for the player - keeping a log of keystrokes to make the correction seem smooth.
In cases where the servers are overloaded, I've seen a strategy that dedicates some of the work like AI to clients. I've seen it in the DayZ mod... Clients take control of some zombies when they get close.

Are there any glaringly obvious or rarely seen strategies or models, errors in the brief descriptions I've listed above, and/or additional reading into the deep parts of this topic?


texts: Has piracy ever resulted in a developer getting shut down?

texts: Has piracy EVER resulted in a developer getting shut down? That is, has piracy ever been so detrimental that it brought about the downfall of a game studio? If I were to release a game, should I be extremely wary of pirates and plan accordingly, or is it safe to assume that it won't damage me or my studio whatsoever?


texts:
I don't know if this issue is in Unity or in my script, the score work well in scoreText, but in the scorePanel its show before last score like it showing 1 rather than 2; the issue doesn't always appear its appear just in specific moment when my score++ and player die nearly in same time, so here is my script.
AddToScore is called with InvokeRepeating, scoreText who show me the correct score, it works well

void AddToScore(){
    score++;
    scoreText.text = score.ToString ();
    mySound.Play();
}

This is when my player Die

void OnCollisionEnter2D(Collision2D other)
{
    Time.timeScale = 0;
    Die ();
}

void Die (){
    Pause.SetActive (false);
    Panel.SetActive (true);
    GameOverPanel.SetActive (true);
    GenerateObstacles.HighScore ();
}

And here is the HighScore from GenerateObstacles

public void HighScore(){
    if (score > highScore) {
        PlayerPrefs.SetInt ("highScore", score);
        highScore = PlayerPrefs.GetInt ("highScore");
        scorePanel.text = score.ToString ();
        highScorePanel.text = highScore.ToString ();
    }
    else if (score <= highScore) {
        highScore = PlayerPrefs.GetInt ("highScore");
        scorePanel.text = score.ToString ();
        highScorePanel.text = highScore.ToString ();
    }
}

Here is a paint to understand


texts: Can someone explain radiosity lighting to me?

texts: I already have the basics of ambient occlusion down.  I have a raycaster and am capable of shooting rays about a hemisphere uniformly.  It seems like those are the basics of what are needed for radiosity but I don't know where to go from there.  Do I find how much light comes from each face?  (I'm making my game out of cubes like minecraft)  After that what do I do?


texts: What are the key considerations I should have when choosing between Phaser 2 and 3?

texts:
I'm planning on experimenting with basic HTML5 game development. Since I'm just learning the ropes I'm sure either engine could support my needs. At the same time I would prefer to focus on the engine/platform that will serve as the best possible foundation when I am ready to produce games. I don't expect to make millions on the games but it seems like a fun hobby that has the potential to bring in a little bit of money.

With that in mind are there any considerations or trade-offs I should be aware of between Phaser 2 and Phaser 3? Is it as simple as the bigger the version number the more awesome sauce included, so Phaser 3 is the natural choice? Based on the research I've done it seems like Phaser 2 will still undergo improvements/bug fixes as a community supported product so it isn't like Phaser 2 is abandoned in favor of Phaser 3. I also saw that the rendering engine was changed between Phaser 2 and Phaser 3. Should this be a major consideration even though I don't have the art skills nor budget to hire an artist so I can create flashy games? Or alternatively is deciding between these two engines so meaningless that I may as well just flip a coin?


texts: Export into several files with custom XNA content pipeline?

texts:
In order to implement a basic Ubershader (a shader which is compiled numerous times with different directives (defines)) I wrote a custom shader processor in XNA. My processor outputs a dictionarry full of compiled shaders, from which I pick the needed shader at runtime. Unfortunately the final dictionarry is so large, it takes a tone of time to load into memmory when the program starts. So I wonder if it is possible to export my results into several XNA output files, which I can load one at a time (and not all at once), calling Content.Load<Effect>("Name")?

I know how to specify an output type for a single output file:

public class PSProcessor : ContentProcessor<EffectContent, Dictionary<string, object>>

It's the second parameter in triangular brackets, but what if I want several files to be created?


texts: Radiometric quantities and time in rendering

texts:
Often in papers people use various radiometric quantities, mostly radiant flux, radiant intensity, radiance and irradiance.

It seems to me that all of these quantities are dependent on time. For example, radiant flux is defined as the amount of radiant energy per span of time (emitted by a light source). The other quantities contain radiant flux in some measure so they seem to depend on time as well.

Yet when reading papers, people don't go into time at all. For example, some papers say "the radiant flux diffusely reflected by this area of the surface is x" and then they go on to explain that x is just light_colored_intensity * surface_color or something (depending on the illumination model used, of course), not factoring in any kind of time at all.

Is this because the time frames observed are assumed to be 1 second? Is the time factored out somewhere (perhaps when defining the light intensity, which may be defined as radiant flux)? What am I misunderstanding here?


texts: Can't read .cso files but I can read their .hlsl versions?

texts:
Well I've been trying to read a .cso file to use as a shader for a DirectX program I'm currently making.

Problem is no matter how I implemented a way to read the file it never worked. And after fidgeting around I discover that it's only the .cso files I can't read.

I can read anything else (which means it works) even their .hlsl files. Which is strange because the .hlsl (high level shader language) files are supposed to turn into .cso (compiled shader object) files.

What I'm currently doing is:

vector<byte> Read(string File){
    vector<byte> Text;
    fstream file(File, ios::in | ios::ate | ios::binary);

    if(file.is_open()){
        Text.resize(file.tellg());
        file.seekg(0 , ios::beg);
        file.read(reinterpret_cast<char*>(&Text[0]), Text.size());
        file.close();
    }

    return Text;
};

If I then implement it.

Read("VertexShader.hlsl"); //Works
Read("VertexShader.cso"); //Doesn't Works?!?!

And I need the .cso version of the shader to draw my sexy triangles. Without it my life and application will never continue and I have no idea what could be wrong.

EDIT #1:
When I read the .hlsl file the vector get's filled whit what was written in the file.
For the .cso ones the function doesn't even pass the "if(file.is_open)" test and stays empty.


texts: How to compile with OpenGL ES on Windows?

texts:
I downloaded OpenGL ES 3.1 sdk here.

But when I tried to run (or compile and run) the executable in "samples" directory, I got the following message:

  The program can't start because libGLESv2.dll is missing from your computer. Try reinstalling the program to fix the problem.

This sounds strange, because the sample program is directly linked with libGLESv2.lib, so it shouldn't even look for dll files.

But when I wanted to install dll files (libGLESv2.dll and libEGL.dll), I got the following error:

regsvr32 libGLESv2.dll

  The module "libGLESv2.dll" was loaded but the entry-point DllRegisterServer was not found.
  Make sure that "libGLESv2.dll" is a valid DLL or OCX file and try again.

So it looks like these dll files are kind of invalid.

Is the problem from my dll files? Or did I miss something in installation process?


texts:
I need help, I can't find a solution to open camera device in my libgdx app. I'm developing it only in Android for now but I have this issue.
I need only to open the preview view, no snap picture o make video... I followed this example but I found this unhelpful.

https://github.com/libgdx/libgdx/wiki/Integrating-libgdx-and-the-device-camera

Have you other resource to do that?

Thanks


texts: How can I draw 500 million triangles with OpenGL?

texts:
I am a beginner. I have a problem with my frame rate. I am trying to see my GPUs maximum performance with using VBO. I saw that everybody says a GPU can draw 1 billion triangles (so 3 billion vertices) with VBO easily, is it right? If it is right, then why am I getting 37 FPS at only 8 million triangles (24 million vertices)?

I am not using a shader and I don't know how to use it.

My GPU is (amd radeon hd 6870).

When drawing 20k triangles, the frame rate is 6000, when drawing 8 million triangles, the frame rate is 37 and CPU usage 1%. I don't think the CPU is the bottleneck..

My code is like this:

I create in header file

GLuint terrainVBO;

I made an init() function:

glGenBuffers(1,&terrainVBO);
glBindBuffer(GL_ARRAY_BUFFER,terrainVBO);
glBufferData(GL_ARRAY_BUFFER,terrainVertices.size()*sizeof(terrainVec),&terrainVertices[0],GL_STATIC_DRAW);

and draw in my main loop:

glBindBuffer(GL_ARRAY_BUFFER,terrainVBO);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3,GL_FLOAT,3*sizeof(float),0);

glDrawArrays(GL_TRIANGLES,0,terrainVertices.size());

glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER,0);

Summary: How can I draw 500-600 millions triangles (1.5 billion vertices) with a good frame rate? I could only draw 8 million triangles.


texts: Is there an algorithm to construct lines (sets of grid points which are all connected) from an unsorted set of grid points?

texts:
I have a 2d square grid used for pathfinding that I wish to convert into a navigation mesh.  My idea is to pluck out all of the nodes that are on the edge of walkable space, simplify the amount of data with a line reduction algorithm, then triangulate the set of points.  I am stuck at the simplifying step.

To find edge nodes I use a marching squares algorithm.  The downside to using marching squares is that the points are unsorted, and in order to pass the points into the Ramer-Douglas-Peucker algorithm they need to be sorted by connectivity (and separated into individual lines).  I'm looking for an algorithm that can either sort my collection by connectivity or discover edge nodes in a consecutive manner.

I'm trying out Djikstra search to find a path from one point to the next.  To determine if these points are connected, during path reconstruction if the parent point has a Euclidean distance greater than 1 to the current point then they are not directly connected.  I might be able to get this to work but it is proving to be extremely slow.

Here are screenshots of the graph I am working with:

2d pathfinding grid:

unsorted edge nodes discovered via marching squares: