texts:
I'd like to write multiple values (not just the color and depth value) in one pass to avoid redundancy in vertex shader. Therefore, i attach multiple (let's say two) color buffers (e.g. textures) to a frame buffer object.
As i read, GLES 3.0 supports GLSL 3.0 which supports layout( location = # ) qualifiers. However, the shaders do not compile with the error message "Typename expected, found 'layout'\n"

Simple fragment shader example:

uniform sampler2D uTexture;
varying vec3 vNormal;
layout( location = 0 ) out vec4 color;
layout( location = 1 ) out vec3 normal;
void main() {
    color = texture2D( uTexture, vTexture );
    normal = normalize( vNormal );
}

I would expect color going to GL_COLOR_ATTACHMENT0 and normal going to GL_COLOR_ATTACHMENT1. So, is there a way to avoid multiple passes in GLES 3.0?


texts: How does an interruptive combat animation system like Metroid 2 work?

texts:
See here for reference.

For the most part this game is a 2D side scroller with the expected platformer architecture: move left, right, jump, shoot, etc. Enemies move and you jump out of the way or shoot them.

But at 0:50 in the video, a well-timed button press interrupts the game's otherwise predictive behavior. The play does a physical attack that slows down the game, the camera moves in, and a barrage of attacks on the enemy are released.

So, how does the enemy model know how to animate based on being hit? Ok for a better example of a bigger enemy, check out 1:13.

The enemy hangs in the air due to the slow mo, and then the player rushes, grabs the tail, throws the enemy down, and is fired upon all while sort of abiding by the game's mechanics. What I mean by sort of: in the enemy flashes white briefly when getting his as he would in a normal scenario. But what happened to the player model? Does the sequence of the player and the monster become one model as it animates or are there two separate models and they're timed just right to appear as though they are interacting? It also boggles my mind because the enemies appear to slow down while the player proceeds to move at their own pace when when throwing the enemy around. That leads me to think its an animation and not a coded behavior.

How what does the code for counter attacks look like? I've never written a game that has the ability for counter attacks. Imagine if there were multiple enemies attempting to counter attack how does the engine manage a scenario like that?


texts: How to make a rigidbody come to rest faster

texts:
I'm trying to move around a 3D rigidbody in Unity 2018.1.0f2 Personal. I am using a C# script with the basic vector3 and velocity stuff from a YouTube video:

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

public class Player : MonoBehaviour {
    [SerializeField]
    private Rigidbody playerBody;

    private Vector3 inputVector;

    private float xMovement;
    private float zMovement;

    [SerializeField]
    private float playerSpeed;

    private float maxSpeed;

    // Use this for initialization
    void Start () {
        playerBody = GetComponent<Rigidbody>();
        playerSpeed = 1;

    }

    // Update is called once per frame
    void Update () {
        xMovement = Input.GetAxisRaw("Horizontal")* playerSpeed;
        zMovement = Input.GetAxisRaw("Vertical") * playerSpeed;

        inputVector = new Vector3(xMovement, playerBody.velocity.y, zMovement);
        playerBody.velocity = inputVector;
    }
}

It works great with a cube I put it on, except for this: if I move the rigidbody and then stop, it takes a long time for it rotate from go only one of the edges or corners just touching the ground (screenshot of what I mean, another screenshot) to resting flat. How can I make it fall back to stability faster?


texts: How to prevent crafting costs and selling prices to converge in economies?

texts:
There is a pattern in player driven economies, where the production (or crafting) costs and the selling prices of items converge to a point where the profit margin becomes minuscule or even negative. Examples which come to mind are World of Warcraft and Eve Online, but I am sure you may recognize this pattern in other games (primarily MMOs) as well.

A simple example:
Reagent costs for a health potion is 1.0 gold in total.
Crafting process requires only some seconds.
Putting an item into the auction house costs 0.1 gold.
The auction house price ranges around ~1.1 gold.
Expected total profit is around ~0.0 gold.
Player invested 200 gold in order to achieve the crafting skill needed to produce it.

In EVE Online players are forced to have high skill in production and marketing in order to have any profits at all. For newcomers it's near impossible to do any production related activity which is even remotely worth the time.

Why is this a problem?
It renders crafting to be more costly than beneficial in the very most cases. However, players should be incentivized to do crafting as some secondary activity, and not be financially punished for practicing it.

So a solution which comes to my mind is to create a better crafting system (but how?). However the fundamental issue might be the natural effects of market economies. It is not unfamiliar to the real economy to follow the same pattern. It's a price mechanism to prevent over-saturation and challenge business sustainability: If your product costs more than its production, that business is not sustainable; and if there is too much competition, you have to set your prices too low in order to keep up.

Let's stick to WoW and EVE Online as basic reference examples.
The questions are:

Is this an issue at all which deserves to be fixed? Can it be fixed at all on a large scale?
How can you fix it, or at least reduce that price pattern from occurring that much?
Is there a way to have that solution remain being free market based and player driven?


texts: How to make my character slide (not bounce) off a slope

texts:
My character needs to slide and not bounce off a slope.

The solutions I found here use a Reflection vector, but they make my character bouncy when they run downwards a slope.

var reflectVector = normal.clone().multiplyScalar(-this.velocity.clone().dot(normal));
this.velocity.addSelf(reflectVector);

How can I make my character simply stick to the terrain when they walk?


texts:
I'm using sprites made up of very few pixels. When scaling the sprite gets blurry, so how do I disable this smoothing? I couldn't find anything in the docs or elsewhere online

Sprite:

In pyglet, scaled 8:


texts: Zooming in a lot without having 3D objects disappear in the Unity Editor

texts: I'm editing the 2D colliders on some objects of my game, and I need them to be very accurate, so I'm zooming in a lot. Problem is, since my objects are 3D graphically, when I zoom in a lot they disappear and I can' t just tap "2D" in the Scene view to fix this. Pressing "F" on the whole object doesn't help a lot, since I have an empty parent with the mesh and colliders as separate objects, and when I select the collider to edit it I only see the collider anyway. Does anyone have any clue on how to proceed?


texts:
I'm working on a Windows phone game and I'm having difficulty with the sprite movement. What I want to do is make the sprite gradually move to the position that is touched on screen, when there is only one quick touch and release. At the minute all I can do is either make the sprite jump instantly to the touch location or move along to the touch location when the touch is held down.

Code for jumping to touch location:

TouchCollection touchCollection = TouchPanel.GetState();
    foreach (TouchLocation tl in touchCollection)
    {
        if ((tl.State == TouchLocationState.Pressed)
             || (tl.State == TouchLocationState.Moved))
        {
            Vector2 newPos = new Vector2(tl.Position.X,tl.Position.Y);

                if (position != newPos)
                {
                    while (position.X < newPos.X)
                    {
                        position.X += (float)theGameTime.ElapsedGameTime.Milliseconds / 10.0f * spriteDirectionRight;
                    }
                }
        }
    }

Code to gradually move along while touch is held:

TouchCollection touchCollection = TouchPanel.GetState();
    foreach (TouchLocation tl in touchCollection)
    {
        if ((tl.State == TouchLocationState.Pressed)
             || (tl.State == TouchLocationState.Moved))
        {
            Vector2 newPos = new Vector2(tl.Position.X,tl.Position.Y);

                if (position != newPos)
                {

                        position.X += (float)theGameTime.ElapsedGameTime.Milliseconds / 10.0f * spriteDirectionRight;

                }
        }
     }

These are in the Update() method of the Sprite class.


texts: Where to find designers for independent projects?

texts:
Let's say I'm a programmer, I know some artists, we've got a game engine and fun prototype done, and we're ready to enter the indie equivalent of "production".

But the game is full of "programmer design" (and/or "artist design"). We've got a core design concept, but average level design, average AI patterns, average writing, poor balance here and there.

Other questions have covered how to help independent developers find programmers and artists. Where can independent artists and programmers find designers? People who can refine and extend the design elements of the game until they really stand out.


texts: How do I create an empty Prefab with Unity 2018.3?

texts:
I was using Unity 2018.1.(something), where I could simply create an empty Prefab object, then drag a Game Object to the Prefab from the Hierarchy to fill it. When I updated to Unity 2018.3.0f2, I don't see any more empty Prefab object in the create menu, all I get is Prefab Variant (which is disabled).

I read the Unity Blog talking about new prefab workflows, and I could not find any changes in how Prefabs are created.


texts: Alternatives for publishing code for a game I'm going to sell?

texts:
I'm developing a game. I want to publish the source code (e.g. on GitHub) for others to review and get ideas from. But I want to sell the game at a later point. That might be much later though.
What are my alternatives here?  The game will likely not have a lot of graphical assets, so just leaving them out won't do much good.
Or can I license it with a somewhat restrictive open source license and then simply unpublish it as soon as I am getting close to start selling it? What open source license would then be most restrictive?
Are there perhaps any other good examples of this?


texts: Compare Mouse X,Y with Grid X,Y to find the closest grid position

texts:
EDIT:
From two very good answers I have decided to use isometric projection instead of my silly grid of cordinates.

I am doing a game entirely in canvas, and I find it quite troublesome right now.

I felt silly trying to post the grid. Here is the code with the grid on hastebin.com

Hastebin Link

Since I have all the grid cordinates, I am iterating the 2D array and turn each iteration into a vertex that I compare to the mouse vertex.
My goal is to find the vertex closest to the mouse vertex.
Instead all I am returning right now is (17,0) every time, no matter where I click.  Do you have any idea why?

function mouse_click(ev) {
    var x = ev.clientX - c.offsetLeft;
    var y = ev.clientY - c.offsetTop;
    // Run click_grid
    alert(click_grid(x,y));

}

// Find the grid that is nearest the clicked cordinates.
function click_grid(xx,yy){
    var result = [];
    var result2 = [];
    var best = [0,0];
    var lastNode = [];
    var currentNode = 9000;
    for(var y = 0;y < 18; y++){
        for(var x = 0; x < 18; x++){
            // Distance = |P-E| = |(3,3)-(1,2)| = |(2,1)| = sqrt(2'2+1'2) = sqrt(5) = 2.23
            result = [grid.grid_x[y][x] - yy,grid.grid_y[y][x] - xx];
            result2 = [result[0] * result[0], result[1] * result[1]];
            currentNode = Math.sqrt(result2[0] + result2[1]);
            if(currentNode < lastNode){
                best = [y,x];
            }
            lastNode = currentNode;
        }
    }
    return([best]);
}


texts: I cannot update a shader constant via a constant buffer in DirectX 11

texts:
I've tried everything I can think of, but I cannot get a constant buffer to update a variable in my shader in DirectX 11. I followed the examples on msdn. I read and re-read the articles on constant buffers. I even followed the nearly identical thread on this site. But for some reason I simply cannot get this to work. Can someone point me in the right direction?

Here's the relevant code:

//my data variable to keep everything together
struct VS_CONSTANT_BUFFER
{
    D3DXMATRIX mWorldViewProj;
    D3DXVECTOR4 vSomeVectorThatMayBeNeededByASpecificShader;
    float fSomeFloatThatMayBeNeededByASpecificShader;
    float fTime;
    float fSomeFloatThatMayBeNeededByASpecificShader2;
    float fSomeFloatThatMayBeNeededByASpecificShader3;
};
    //I initialize my data variable
    D3DXMATRIX identity;
D3DXMatrixIdentity( &identity );
m_ConstantBufferContents.mWorldViewProj = identity;
m_ConstantBufferContents.vSomeVectorThatMayBeNeededByASpecificShader = D3DXVECTOR4(1,2,3,4);
m_ConstantBufferContents.fSomeFloatThatMayBeNeededByASpecificShader = 3.0f;
m_ConstantBufferContents.fTime = 1.0f;
m_ConstantBufferContents.fSomeFloatThatMayBeNeededByASpecificShader2 = 2.0f;
m_ConstantBufferContents.fSomeFloatThatMayBeNeededByASpecificShader3 = 4.0f;

// Fill in a buffer description.
D3D11_BUFFER_DESC cbDesc;
cbDesc.ByteWidth = sizeof( VS_CONSTANT_BUFFER );
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbDesc.MiscFlags = 0;
cbDesc.StructureByteStride = 0;

// Fill in the subresource data.
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = &m_ConstantBufferContents;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;

// Create the buffer.
HRESULT hr = pDevice->CreateBuffer( &cbDesc, &InitData, &m_ConstantBuffer );

    //from my update function, I update the contents of my buffer like so

m_ConstantBufferContents.mWorldViewProj = view;
// Set the buffer.
pDeviceContext->UpdateSubresource( m_ConstantBuffer, 0, 0, &m_ConstantBufferContents, 0, 0 );
pDeviceContext->VSSetConstantBuffers( 0, 1, &m_ConstantBuffer );

    //And this is how I attempt to use it in my shader
    //--------------------------------------------------------------------------------------
    // Constant Buffers
    //--------------------------------------------------------------------------------------
    cbuffer cbPerObject : register( b0 )
    {
       matrix  g_mWorldViewProjection  : packoffset( c0 );
       matrix  g_mWorld                : packoffset( c4 );
       float4  g_MaterialAmbientColor  : packoffset( c8 );
       float4  g_MaterialDiffuseColor  : packoffset( c9 );
    }

I'm sure it's something simple and stupid that I've overlooked, but I cannot seem to find the problem myself. Any ideas?

Goishin


texts: Optimize algorithm: finding all possible moves for a turn based game

texts:
I am working on the ai for a turn based game. To illustrate my problem this are the simplified rules of the game:

The game takes place on a tiled map with obstacles (black quads) like this:

The player has several tokens (like the two colored dots in the example picture)
The player can move all his tokens in his turn
the tokens move in a straight line until they hit an obstacle, the border of the map or another token
each token could move two times in each turn.
the player can move his tokens in any order he likes

The AI needs a list of all possible turns it could make of one game state. My first attempt was to recursively go through all tokens and move them in any possible direction and order. that works of course but the problem is that with just four tokens there are several millions of possible turns (if each token could move two times). Most of the outcomes of these turns are the same (the tokens end in the same place). In the example above the tokens could move like this:

No matter in which order the four move actions (A,B,C,D) are made, the end positions of the tokens are the same. I am only interested in the possible end turn situations. So I implemented a transposition table in the turn generation algorithm to negate all of the equal turns. That works and in the end I have only several hundred of possible turns with four tokens rather than several millions.
The problem is that the algorithm takes too much time because it has to calculate every possible turn. Does anybody has a hint how to prune the turn generation  tree? Or any other idea how to calculate only the different possible turn outcomes?

Note: In the real game the map is slightly bigger (30-40 free cells) and there are up to 6 tokens.


texts: How do I colorize a texture with libGDX?

texts:
I'm working on a libGDX implementation for my library which draws ASCII tiles to create a text GUI. My current Swing + BufferedImage implementation looks like this:

This works by copying parts of a grayscale texture which has CP437 characters on it and transforming them by adding color to each pixel.

My problem is that my libGDX implementation does not work for some reason:

What I have tried is this:

    val backend: TextureRegion = region.getBackend()

    val texture = backend.texture
    if (!texture.textureData.isPrepared) {
        texture.textureData.prepare()
    }
    val pixmap = texture.textureData.consumePixmap()
    (0 until backend.regionWidth).forEach { x ->
        (0 until backend.regionHeight).forEach { y ->
            val color = Color(pixmap.getPixel(backend.regionX + x, backend.regionY + y))

            val ax = color.a
            var rx = color.r
            var gx = color.g
            var bx = color.b
            rx *= r
            gx *= g
            bx *= b
            if (ax < 50) {
                pixmap.drawPixel(backend.regionX + x, backend.regionY + y, textCharacter.getBackgroundColor().toAWTColor().rgb)
            } else {
                pixmap.drawPixel(backend.regionX + x, backend.regionY + y, Color(rx, gx, bx, ax).toIntBits())
            }
        }
    }

    return region

I know that I am missing something but I just can't figure out what the problem is here. I've tried with various options like copying the TextureRegion but I can't get this to work.

My other implementation uses BufferedImages and it just works:

    val r = textCharacter.getForegroundColor().getRed().toFloat() / 255
    val g = textCharacter.getForegroundColor().getGreen().toFloat() / 255
    val b = textCharacter.getForegroundColor().getBlue().toFloat() / 255

    val backend: BufferedImage = region.getBackend()
    (0 until backend.width).forEach { x ->
        (0 until backend.height).forEach { y ->
            val ax = backend.colorModel.getAlpha(backend.raster.getDataElements(x, y, null))
            var rx = backend.colorModel.getRed(backend.raster.getDataElements(x, y, null))
            var gx = backend.colorModel.getGreen(backend.raster.getDataElements(x, y, null))
            var bx = backend.colorModel.getBlue(backend.raster.getDataElements(x, y, null))
            rx = (rx * r).toInt()
            gx = (gx * g).toInt()
            bx = (bx * b).toInt()
            if (ax < 50) {
                backend.setRGB(x, y, textCharacter.getBackgroundColor().toAWTColor().rgb)
            } else {
                backend.setRGB(x, y, (ax shl 24) or (rx shl 16) or (gx shl 8) or (bx shl 0))
            }
        }
    }
    return region

What am I doing wrong?


texts: Why does Ads (Rewarded Video or Intersititals) in games skips when you press home and tap on games icon in Android?

texts:
I have stumbled upon an issue wherein Android when I play rewarded video or any interstitial and do following steps:

In the middle of a video Ad I press the home button
Resume back from background tray the ad plays where I left off.

BUT if,

In the middle of a video Ad I press the home button
Tap on the game icon to resume back then it skips the ad and game continues without getting any reward.

I thought this might be anything specific to my code but then I tried playing many other games including Mr. Bullet, Hospital Inc, Idle LumberJack, Super Salon and the list goes on and all had the same issue.
Is this some android thing? As for iOS, this doesn't happen.
I would like to have some information on why this happens and can we prevent it from happening.
I am using Unity 3D for my game development and AppLovin MAX for ads.


texts: Why (SDL) animated filled-circle leaves trail of movement?

texts:
I'm trying to achieve proper animation using SDL. Used flags are SDL_HWSURFACE and SDL_DOUBLEBUF.

That what I'm getting is technically smooth (I think), but I can figure out what should I do to remove that trail?
My animation is time-based (I'm calculating displacement with delta time).

Link to to video: https://vimeo.com/62065078

my (every-frame) drawing function is like:

for(int x = 0; x < screen->w; ++x)
    for(int y = 0; y < screen->h; ++y)
        draw_pixel(screen, x, y, 136, 136, 136);

and ball:

filledCircleColor(screen, ball.x, ball.y, 17, 0x000000ff);

and finally:

SDL_Flip(screen);

main loop is:

for(;;) {
    curr_ts = stopwatch_seconds_elapsed(sw);
    d_time = curr_ts - prev_ts;
    prev_ts = curr_ts;
    cpSpaceStep(space, d_time);
    draw_scene(screen);
}


texts: Blender to UE4 eye mesh is getting detached

texts:
I've created a rigged and animated mesh using MakeHuman and Blender and exported it as FBX file to be used in Unreal Engine, all seems to be working well except the eyes. I've tried parenting the eye mesh to the head bone which works fine in Blender but unfortunately doesn't work with Unreal Engine. My second approach was to create a bone for each eyes and parent the eye mesh with weights which is better but it's still doesn't work as it shows in blender.
In Blender 2.82 ( works through out the animation )

In UE4 - 4.24.3 ( sometimes the eyes are inside the body, sometimes it pops outside, never in the right place. )


texts: UV mapping doesn't work without duplicating vertices, but duplicating will reduce performance, right? Is there another solution?

texts:
Situation: I've been trying to gradually get a lower and lower level of understanding of how games work, and lately I've been following Rastertek's DirectX 11 tutorials. Of course, I started branching off on my own and experimenting, like a good little programmer.

I noticed that the tutorial had a set of 3 vertices for each triangle, even if that meant duplicating vertices that were there anyway. So a cube would have 12 triangles * 3 vertices/triangle = 36 vertices, when it only needed 8. This seems like it could reduce performance by quite a bit in more complicated models.

However, when I tried setting the indices to reuse vertices, I ran into problems because the normal and UV coords are assigned to each vertex. I averaged the normal vectors, which resulted in smoothing the lighting where it probably shouldn't have been smooth, and UV coords...well...right now they overwrite each other as they're importing, which results in crazy things, like so: http://i.stack.imgur.com/Rr6aB.jpg

My thoughts: Right now, I see one reasonable solution. When UV mapping in Blender, I had to create "seams", which the model was unwrapped around and blah blah, I'm sure you know what that is. Anyway, I could duplicate the vertices on these seams only, which would solve both performance and texturing quite nicely.

This wouldn't require much change in the code I currently have, but Blender's exporting algorithms don't seem to cooperate with this approach. At least not with the .obj format. Getting this approach to work correctly looks entirely possible, but also annoyingly difficult.

Finally, the question: So now I'm here, typing to you people. Am I on the right track? Or is there an entirely different approach I haven't thought of yet? What is the normal way of doing this?

Of course the other question is, will duplicating vertices like that really have a significant impact on performance? My very premise could be mistaken.


texts: How to "aim ahead of" an object moving in a circle?

texts:
Let's say I have a GameObject A that's moving in a circular path in orbit around a central point, and I have a second GameObject B that is capable of independent movement, and can move at a higher velocity than A.  B may be located at an arbitrary point, either inside or outside of A's orbit.  I want to calculate the fastest route that will cause object B to intercept object A.  (The problem is not exactly "I want a spaceship to arrive at a planet", but close enough for the purposes of this question.)

The obvious idea is to compute a bunch of concentric circles around B and use some sort of divide-and-conquer guesswork to narrow in on a circle that ends up touching A's orbit at exactly the point where A would be if B moved to that point at its maximum speed.  But that feels a bit clunky, not to mention computationally expensive for something that I'd want to do fairly frequently, potentially multiple times per frame.  Is there a better way to calculate this?

For simplicity's sake, assume that all calculations are occurring in a 2D plane.


texts:
I have a problem when I store the DistanceScore to text, the problem is why the DistanceScore always storing at text number 1, this happens when I play at level 2 which is the DistanceScore could be store in text number 2and so on, FYI I have 3 levels here.
here the preview

as you can see on the top of level 2 gameplay is distance so when i dead the distance saved and storing to text each level.

and when I go to the main menu the Level 1text updated instead of Level 2.
this is my script:
public Item[] _item;

public int mapIndex;

public enum ITEM_TYPE
{
    LEVEL
}

public ITEM_TYPE _type;

private void Start()
{
    loadItemInformation();
}

public void loadItemInformation()
{
    for (int i = 0; i < _item.Length; i++)
    {
        if (_type == ITEM_TYPE.LEVEL)
        {
            _item[i].bestScore.enabled = true;
            _item[i].distance.enabled = true;

            float distanceUi = PlayerPrefs.GetFloat("distance" + i.ToString());
            float value = PlayerPrefs.GetFloat("Time" + i.ToString());
            float minutes = Mathf.FloorToInt(value / 60);
            float seconds = Mathf.FloorToInt(value % 60);

            if (value == 0)
            {
                _item[i].bestScore.text = "No Record Yet";
            }

            else
            {
                _item[i].distance.text = "Unstopable ";
                _item[i].bestScore.text = "Best Time = " + string.Format("{0:00}:{1:00}", minutes, seconds);
            }

            _item[i].distance.text = "Long distance = " + distanceUi.ToString();

        }
    }
}

}
    [System.Serializable]
    public class Item
    {
        public TextMeshProUGUI bestScore;
        public TextMeshProUGUI distance;
    }

here the distance script:
#region Distance
[Header("Distance")]
public Transform checkPoint;
public TextMeshProUGUI distanceText;
M_GameManager _GameManager;
private float distance;
private float highDistance;
float index;
#endregion

private void Start()
{
    _GameManager = FindObjectOfType<M_GameManager>();
    checkPoint = GameObject.FindGameObjectWithTag("Finish").transform;
    distanceText = GameObject.FindGameObjectWithTag("DistanceTxt").GetComponent<TextMeshProUGUI>();
    index = (float)(PlayerPrefs.GetInt("Level"));// typo here i call it set and now I've fix it
}
index = PlayerPrefs.GetFloat("Level");
distance = (checkPoint.transform.position.x - transform.position.x);
    if (transform.position.x > checkPoint.transform.position.x)
    {
        distance = 0;
        //PlayerPrefs.SetFloat("distance" + index, distance);
    }
    if (_GameManager.isDead || _GameManager.isTimeout || _GameManager.fuelFinished)
    {
        PlayerPrefs.SetFloat("distance" + index, distance);
        PlayerPrefs.Save();
    }
    distanceText.text = distance.ToString("F1") + "m";

and for _item[i].bestScore.text this work to storing each level but why for the distance not working.


texts: I have tried using Unity's new input system, but it's incredibly hard to learn, the documentation is poor, and the old system is much easier to work with.  I would like to revert my project back to the old system, but I am unsure how to do that.  How do i disable the package and reconfigure my project so it will accept code using the old system?


texts: How does glm::lookAt produce a View Matrix?


texts: Implement Fast Inverse Square Root in Javascript?

texts:
The Fast Inverse Square Root from Quake III seems to use a floating-point trick. As I understand, floating-point representation can have some different implementations.

So is it possible to implement the Fast Inverse Square Root in Javascript?

Would it return the same result?

float Q_rsqrt(float number) {

  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y = number;
  i = * ( long * ) &y;
  i = 0x5f3759df - ( i >> 1 );
  y = * ( float * ) &i;
  y = y * ( threehalfs - ( x2 * y * y ) );

  return y;

}


texts:
I make a voxel engine on LWJGL 3 (OpenGL binding for JVM).
I store all object data in world class.
World is subdivided into 32*32*32 chunks.
Chunks use octree storage.
The main part of all my rendering is cubes that share one mesh but have different transformation matrices and some other data.
To render those i use one VAO per chunk, it contains only one cube mesh instance and has all cubes data (like transformations) stored in its VBOs.
I construct each chunk VAO once and render it fully in one call - glDrawElementsInstanced.
If i need to change some cube data in a chunk, i will reconstuct VAO from ground up or change individual buffer data. That should be pretty efficient, right ?

But I need some other stuff to be rendered, like complex mesh objects or effects or some debug stuff.

How should I render those objects ?
Should I create a VAO for each mesh and then perform instanced rendering for each object with the same mesh ?
Or should I batch all objects with their meshes into one VAO for each chunk and render it fully ?

I was trying to create a VAO recently, that contained one instance of each mesh and all object data. But i could not render it correctly. Because each time I needed to somehow switch object data VBO while rendering an instanced mesh. It didn't work.

Code for the last VAO: http://pastebin.com/WanNsR5L


texts: Why does a call to vkCreateInstance() take noticeable time to complete?

texts:
I decided to learn Vulkan and started writing a simple program. I then ran the program (which only called vkCreateInstance()) to see if the Vulkan instance was created successfully and was shocked to see that my computer's fan started spinning loudly (and kept doing so for 5 seconds) and I saw a spike of 8% of the computer's processes being used for a second(and the function call took 1.5 billion cycles -- enough to make the program's loading time noticeable). Complaining about a one second CPU-usage spike would seem humorous if the spike were due to a loop doing hundreds of function calls, but I only called a single function once (vkCreateInstance()). Is there a way to reduce the overhead of some of Vulkan's functions and should I be using Vulkan for 2-D rendering?

Here is the code that took 1.5 billion cycles to run:

VkInstance instance;

VkApplicationInfo appInfo = { 0, 0, 0, 0, 0, 0, 0 };
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Hello Triangle";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;

VkInstanceCreateInfo createInfo = { 0, 0, 0, 0, 0, 0, 0, 0 };
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledExtensionCount = 0;
createInfo.ppEnabledExtensionNames = NULL;

VkResult result = vkCreateInstance(&createInfo, NULL, &instance);


texts: Can a Switch Dev Kit do everything a normal Switch console can do?

texts:
Today, news came out that the Nintendo Switch Dev Kit is only 50,000 yen (around $450-500 USD). I had been planning to buy a normal Nintendo Switch for $300, but since I enjoy making little games in Unity and it's only ~50% more expensive to get a Dev Kit, I thought maybe I'd get a Dev Kit instead of a console.

When I brought up the idea with a friend, they asked, "Can the Dev Kit even play normal games?"

It's an excellent question, and I have no idea what the answer is. I'm hoping people here know. More generally, what draw backs are there from getting a Dev Kit instead of a normal console? Does it weigh significantly more? Is it more bulky or less comfortable to carry around? Does the battery not last as long? Is it even portable? Can it play all the normal retail games that the ordinary console can?


texts:
I have multiple 3d objects in my scenes. These are without any graphics and have different colors and some lights.

I was building all of the scenes with a standard shader and now, when running on an Android device, FPS drops to 30-50. I've already fixed the particles with Mobile shaders, these work well now but I have some problems with normal cubes, spheres etc.

As I read, Standard shader == death on mobiles and here comes my question. I read that I should use one of these from Mobiles tab or Legacy ones.

Which one is better in my case? Which one should I use when I only want to adjust the color of the object ( + support a lightmap ) ?


texts:
I have recently been programming an Entity Component System in Java for a small game that I am working on. From what I have tested, it works rather well however I question the component part. I currently have an Entity class that stores subclasses of  Component in a HashMap which can be accessed by a String:

private Map<String, Component> components = new HashMap<String, Component>();

The problem is that my root Component class looks like this:

public class Component {

}

I feel as if I've headed in the wrong direction so my question is do I need a Component super class? If so, is there anything that needs to be put in it? If not, should I have a HashMap of Objects instead? Are there advantages to either methods?


texts: C++ and OpenGL ES: glDrawArrays calls are time consuming

texts:
Currently, I'm profiling my iOS. All the calls to glDrawArrays are expensive. For example, here is a screenshot of the rendering part of a particle system:

As you can see, the glDrawArrays call takes from that method 39% of the CPU time. While other calls like glUniform1i and glBindVertexArrayOES are very quick. Why isn't glDrawArrays as quick as the others are? Aren't all these methods starting with gl*** short functions that will add a command to the driver queue? So, why does it take longer for a glDrawArrays call to be added to the queue, in comparation with all the other gl calls?

Is this normal, or does this mean that I'm doing something wrong?

In response to doug: Nope, that didn't work. The glFinish() call actually took a while, but the glDrawArrays call is still taking much time in comparation with the state changes (like glBindVertexArrayOES).


texts: How can I create a templated function to add components to their necessary containers using an ECS system?

texts:
I had implemented a basic ECS system and was then informed that it should be changed as each system should not directly store their required components.

I have created a ComponentManager which will own all of the registered components, and I would like to keep all of the different components in their own containers

class ComponentManager
{

    template <typename T> T& AddComponent(Entity entity)
    {
        //...
    }

    std::vector<2DRenderComponent>  m_renderComponents;
    std::vector<TransformComponent> m_transformComponents;
};

I could create a different function for each component type but I would like to get familiar with using templates for tasks like this. It will also make it a little easier further down the line when I try to do more complex tasks.

Could anyone point me in the right direction as to how I would achieve something like this, whilst keeping the components isolated from each other?

My usage would be something like the code below

Entity entity = entityManager->CreateEntity();
TransformComponent& transformComponent = componentManager->AddComponent<TransformComponent>(entity);

When I call AddComponent with a TransformComponent, how do I add it to the correct container (m_transformComponents). If I have to change the structure slightly to get this to work, i.e a map of types to vectors that is fine. Any guidance on this is appreciated.

So after looking into the entt framework, the functionality there is what I want to achieve, on a much smaller scale. Code example of how it functions (https://github.com/skypjack/entt#code-example)

I've done some digging into how they register components through what they describe as a registry (https://github.com/skypjack/entt/blob/master/src/entt/entity/registry.hpp).

From what I can gather after looking they identify component containers by ids but I'm confused as to what it is doing so if someone could help me to understand this it would be appreciated.

First entry point when we want to add a component to a given entity

template<typename Component, typename... Args>
decltype(auto) assign(const entity_type entity, [[maybe_unused]] Args &&... args) {
    ENTT_ASSERT(valid(entity));
    return assure<Component>()->assign(*this, entity, std::forward<Args>(args)...);
}

assure() is called to obtain the correct pool for the component being added

template<typename Component>
const pool_type<Component> * assure() const {
    const auto ctype = to_integer(type<Component>());

    //....
}

type function - this returns what I can see to be an enum? But how is the function constructing and returning an enum like it does. When I try this in a separate application it fails to compile

    ENTT_OPAQUE_TYPE(component, ENTT_ID_TYPE) //enum is created from this macro, along with the to_integer function

//macro
#define ENTT_OPAQUE_TYPE(clazz, type)\
    enum class clazz: type {};\
    constexpr auto to_integer(const clazz id) ENTT_NOEXCEPT {\
        return std::underlying_type_t<clazz>(id);\
    }

template<typename Component>
static component type() ENTT_NOEXCEPT {
    return component{runtime_type<Component, component_family>()}; //how is this compiling?
}

runtime_type function - ENTT_ID_TYPE is defined as std::uint32_t

#define ENTT_ID_TYPE std::uint32_t

    template<typename Type, typename Family>
    static ENTT_ID_TYPE runtime_type() ENTT_NOEXCEPT {
        if constexpr(is_named_type_v<Type>) {
            return named_type_traits<Type>::value;
           //this looks like it returns a hashed string of the type name as std::uint32_t
        } else {
            return Family::template type<Type>;
        }
    }


texts: C/C++ code to generate texture coordinates for a curved surface

texts:
I have a triangular mesh of a surface curved in two directions, e.g. a sphere. It is therefore not possible to roll this surface flat (essentially specifying a mapping to U,V texture coordinates) without distorting some of the triangles. Does anyone know of a C++ library that can take the mesh as input and produce as output suitable U,V texture coordinates for each mesh vertex, such that the resulting implied texture map distorts the triangles as little as possible?

EDIT:
An example of this process is described in this paper - "Least Squares Conformal Maps for Automatic Texture Atlas Generation". I'm basically after an implementation of that, or something which does the same thing.


texts: 2D Bounding box for collision detection - alternate shapes

texts:
I have objects in my game such as clouds and stars.  I have given the bounds for them in rectangle format.

The images are not rectangular, although the collision boxes are.  How can I implement a collision box that is exactly the shape of my character?

I'm suing overlap2D.


texts:
I implemented a simple deferred shading renderer.
I use 3 G-Buffer for storing position (R32F), normal (G16R16F) and albedo (ARGB8).
I use sphere map algorithm to store normals in world space.
Currently I use inverse of view * projection matrix to calculate the position of each pixel from stored depth value.

First I want to avoid per pixel matrix multiplication for calculating the position. Is there another way to store and calculate position in G-Buffer without the need of matrix multiplication
Store the normal in view space

Every lighting in my engine is in world space and I want do the lighting in view space to speed up my lighting pass.

I want an optimized lighting pass for my deferred engine.


texts: How do I get 'getchar()' to not block the input?

texts:
I am working on designing a pong like game but converting a getchar() to getch() and getche(), respectively, but getchar() is blocking the input. I am using C++ code, and while there is the ncurses library, I heard that this is a better approach; I am only needing to update this one command.

How do I get getchar() to not block the input?

The code is as follows:

#include<iostream>
#include <termios.h>
#include <stdio.h>

//Prototypes
char inputReader();
void updateWorld();
void renderWorld();
void initTermios(int echo);
void resetTermios(void);
char getch_(int echo);
char getch(void);
char getche(void);

static struct termios oldChars, newChars;
int main()
{
   bool running = true;

   do
   {
      if(getche() == 'q')
      {
         running = false;
      }
      updateWorld();
      renderWorld();
   }

   while(running);
   std::cout << "I exited the loop";
   return 0;
}

char inputReader()
{
   return getch();
}

void updateWorld()
{
  std::cout << "I am updating the world" << std::endl;
}

void renderWorld() {}

void initTermios(int echo) //struct termios &oldChars, struct termios &newChars)
{
  tcgetattr(0, &oldChars); /* grab old terminal i/o settings */
  newChars = oldChars; /* make new settings same as old settings */
  newChars.c_lflag &= ~ICANON; /* disable buffered i/o */
  newChars.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
  tcsetattr(0, TCSANOW, &newChars); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void)//struct termios &oldChars)
{
  tcsetattr(0, TCSANOW, &oldChars);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
  char ch;
  initTermios(echo); //oldChars, newChars);
  ch = getchar();
  resetTermios();//oldChars);
  return ch;
}

/* Read 1 character without echo */
char getch(void)
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void)
{
  return getch_(1);
}


texts:
I recently created a map editor, and i came across a problem: I can't position some tiles on some grid blocks, but if i go farther from Y-axis near 0, i can place blocks correctly.

This is the video: Test_001

Map.cpp - createBlock func

void Map::createBlock(sf::Vector2f position, std::string name) {
        double gridPositionX = floor(position.x / grid) * grid;
        double gridPositionY = floor(position.y / grid) * grid;

        double ceiledGridPositionX = ceil(gridPositionX);
        double ceiledGridPositionY = ceil(gridPositionY);

        int mapPositionArrayX = ceiledGridPositionX / grid;
        int mapPositionArrayY = ceiledGridPositionY / grid;

        sf::Vector2f gridPosition( ceiledGridPositionX, ceiledGridPositionY );

        if (!isPositionOccupiedByBlock(mapPositionArrayX, mapPositionArrayY)) {
            Block block = blockTypes[ findBlockNameVector(name) ];
            block.setPosition(gridPosition);

            worldBlocks.push_back(block);
            wMap[ mapPositionArrayX ][ mapPositionArrayY ] = block.getID();
        }
    }

bool Map::isPositionOccupiedByBlock(int mapX, int mapY) {
    return (wMap[mapX][mapY] != 0) ? true : false;
}


texts: How do I check if animation is of Animation Type "Humanoid"?

texts:
One can set the Rig / Animation type of an animation to "Generic", "Humanoid", etc.

How could I check by script if an animation rig has been set to type "Humanoid"?


texts: How to use C++11 chrono header for a clock

texts:
In first, sorry for my bad english. :)
I'm making a game using SFML and C++11 new features, but I've got a problem with my custom Clock class (made to replace the SFML one).
When I get the elapsed time since the clock instanciation, it returns it in microseconds. But I'd want it to return nanoseconds, I don't understand what happens.
My question is, why do I get microseconds instead of nanoseconds ?
Here is my main :

#include "clock.h"
#include <SFML/Window.hpp>
#include <iostream>

int main() {
    sf::Window window(sf::VideoMode(800,600), "title");
    sf::Event event;
    window.setFramerateLimit(60);
    Clock<std::chrono::nanoseconds> clock;

    while(window.isOpen()) {
        while(window.pollEvent(event)) {
            if(event.type == sf::Event::Closed) window.close();
        }

        std::cout << clock.Restart().count() << std::endl;
        /* I would like it to print about 16666666 (ns), but it prints about 16666 (μs) */

        window.display();
    }

    return 0;
}

And there is my Clock.h file :

#ifndef CLOCK_H
#define CLOCK_H

#include <chrono>

template < typename Period >
class Clock {
public:
                                                                    Clock();
    Period                                                          GetElapsedTime() const;
    Period                                                          Restart();

private:
    std::chrono::time_point< std::chrono::high_resolution_clock >   mTimePoint;
};

template < typename Period >
Clock< Period >::Clock()
    : mTimePoint( std::chrono::high_resolution_clock::now() ) {
}

template < typename Period >
Period Clock< Period >::GetElapsedTime() const {
    const Period elapsedTime( std::chrono::high_resolution_clock::now() - mTimePoint );
    // Here, elapsedTime.count() equals ~16666 too, but I want nanoseconds, so why ?!
    return elapsedTime;
}

template < typename Period >
Period Clock< Period >::Restart() {
    const Period period( GetElapsedTime() );
    mTimePoint = std::chrono::high_resolution_clock::now();
    return period;
}

#endif // CLOCK_H


texts: High volume sprite management in entity component system

texts:
I'm working on an entity-component-system based 2.5d game. That is, entities are groups of components that are processed by systems.
I am having a hard time seeing how a sprite rendering system, that targets entities with a "RenderableSprites" component, can effectively manage components when processing so that only sprites that are on screen are iterated and subsequently drawn.
I can see various solutions with LINQ etc. but they all require iteration through the collection of components whether explicit or not.

What is the common practice to deal with this problem, even if not in the paradigm of entity component systems?

To solve this problem with my tile based "floor" entity, it was best to group the floor tiles into one entity whereas before they were separate. This allows indexing of  tiles by position in a tilemap so that every update step (to be later limited to updates where camera movement is detected), tiles are methodically selected rather than filtered via iteration and propagated to the "RenderableSprites" component, hence tiles that are not on screen are not processed in the draw step.

I am now adding scenery entities, but it doesn't scale particularly well when each tree is a seperate entity. Any suggestions as to whether scenery should be grouped into one entity? This seems to defeat the point of an entity component system and my spidey senses tell me this will lead to difficulty calculating collision etc.

Any feedback much appreciated!
I am working in XNA but I don't consider this a very language specific question.

To anyone interested:
I'm in the processing of working around this; I am constructing an entity manager storing entities by ID, something I should have done earlier. This will allow me to maintain some spatial indexes against entity IDs that the sprite renderer can reference before selecting which entities to process from the manager. This is as opposed to each System holding concrete references to its target components. I will maybe post some code when I'm done.


texts:
I'm trying to port a blur effect from an XNA project over to SharpDx, and I get a "Null Reference Exception" wich I'm unable to find the reason for.

    private void blurShadow(RenderTarget2D to, RenderTarget2D from, int dir)
    {
        _graphicsDevice.SetRenderTargets(to);
        _shadowBlurEffect.CurrentTechnique.Passes[dir].Apply();
        _spriteBatch.Begin(SpriteSortMode.Deferred, _shadowBlurEffect);
        _spriteBatch.Draw(from, Vector2.Zero, Color.White);
        _spriteBatch.End();  // <-- Null Reference Exception here
    }

    public void Draw()
    {
        _graphicsDevice.SetRenderTargets(_graphicsDevice.DepthStencilBuffer, ShadowDepthTarget);
        _graphicsDevice.Clear(Color.White); // Clear the render target to 1 (infinite depth)
        foreach (var obj in ShadowCastingObjects)
            obj.Draw(Camera, DrawingReason.ShadowDepthMap, this);

        blurShadow(_shadowBlurTarg, ShadowDepthTarget, 0);
        blurShadow(ShadowDepthTarget, _shadowBlurTarg, 1);

        _graphicsDevice.SetRenderTargets(_graphicsDevice.DepthStencilBuffer, _graphicsDevice.BackBuffer);
    }

The render targets are created like this:

    ShadowDepthTarget = RenderTarget2D.New(_graphicsDevice, width, height, PixelFormat.R16G16.Float);
    _shadowBlurTarg = RenderTarget2D.New(_graphicsDevice, width, height, PixelFormat.R16G16.Float);

This is the shader code, I have tried variuos versions of the method signatures - in vain:

Texture2D Texture;
SamplerState TextureSampler;

// Precalculated weights and offsets
float weights[15] = { 0.1061154, 0.1028506, 0.1028506, 0.09364651, 0.09364651,
    0.0801001, 0.0801001, 0.06436224, 0.06436224, 0.04858317, 0.04858317,
    0.03445063, 0.03445063, 0.02294906, 0.02294906 };

float offsets[15] = { 0, 0.00125, -0.00125, 0.002916667, -0.002916667,
    0.004583334, -0.004583334, 0.00625, -0.00625, 0.007916667, -0.007916667,
    0.009583334, -0.009583334, 0.01125, -0.01125 };

float4 BlurHorizontal(
    float2 UV : TEXCOORD0) : SV_Target
{
    float4 output = float4(0, 0, 0, 1);
    for (int i = 0; i < 15; i++)
        output += Texture.Sample(TextureSampler, UV + float2(offsets[i], 0)) * weights[i];
    return output;
}

float4 BlurVertical(
    float2 UV : TEXCOORD0) : SV_Target
{
    float4 output = float4(0, 0, 0, 1);
    for (int i = 0; i < 15; i++)
        output += Texture.Sample(TextureSampler, UV + float2(0, offsets[i])) * weights[i];
    return output;
}

technique Tech
{
    pass Horizontal
    {
        SetGeometryShader(0);
        SetVertexShader(0);
        SetPixelShader(CompileShader(ps_4_0, BlurHorizontal()));
    }

    pass Verical
    {
        SetGeometryShader(0);
        SetVertexShader(0);
        SetPixelShader(CompileShader(ps_4_0, BlurVertical()));
    }
}


texts: Where in code to for collision? In object class? Mainline code?

texts:
Making a simple game in Love 2D framework where if I click on an object then it disappears.

Do I check to see if I've clicked the enemy inside a function in the enemy object? Or just in my main.lua? Currently I have this code in my main.lua:

function love.mousepressed(x, y, button)
   if button == "l" then
      for i,b in ipairs(bugs) do
         if b:isClicked(x, y) then
            table.remove(bugs, i)
         end
      end
   end
end

Is there a standard design pattern on where this code should belong?


texts: Implementing a scrollable Panel in XNA/MonoGame

texts:
I am trying to create a scrolling Panel for my game. The code I've shown below works but there is a problem.

I read Andrew's answer here and decided to implement the scrolling effect by using a Translation Matrix. However my Controls (Buttons, ComboBoxes, etc.) have a fixed Rectangle on the screen (the Rectangle I'm using to check if the cursor is over the Control). As I found out the Matrix translation will only move the texture of the Control and not the Rectangle.

The Problem:

So if I scroll down and click where the button was initially in the panel, it will trigger the Click event even though the button texture is "outside" the scissorRectangle.

What I considered:

I thought I should disable interaction with Controls outside of the scissorRectangle, but what about controls that are still partially visible?
If Matrix Translation won't work I thought about iterating over the Panel's _controls List and sending the offset to each individual Control (ugh), where it will adjust its Rectangle position. :/

I've got the following code for my Panel:

// ...
private RasterizerState _rasterizerState = new RasterizerState() { ScissorTestEnable = true };
private Vector2 _scrollOffset = Vector2.Zero;
private Matrix _matrix = Matrix.Identity;
// ...

In Update():

_matrix = Matrix.CreateTranslation(new Vector3(_scrollOffset, 0));
if (Enabled && BorderBox.Intersects(inputManager.MouseRect))
{
    if (inputManager.ScrolledDown())
    {
        if (_combinedRowHeight - (ContentBox.Height -_scrollOffset.Y) > -_combinedTextHeight)
        {
            _scrollOffset.Y -= 14;
        }
    }
    else if (inputManager.ScrolledUp())
    {
        if (_scrollOffset.Y < 0)
        {
            _scrollOffset.Y += 14;
        }
    }
}

And then in Draw():

// Save the previous RasterizerState
RasterizerState oldState = spriteBatch.GraphicsDevice.RasterizerState;
// Save the initial scissor rectangle
Rectangle currentScissorRect = spriteBatch.GraphicsDevice.ScissorRectangle;

spriteBatch.End();

spriteBatch.Begin();
// Draw Panel
spriteBatch.End();

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, rasterizerState: _rasterizerState, transformMatrix: _matrix);

spriteBatch.GraphicsDevice.ScissorRectangle = ContentBox;

if (_drawControls)
{
    for (int i = 0; i < _rows.Count; i++)
    {
        _rows[i].Draw(spriteBatch);
    }
}

spriteBatch.End();

// Restore the scissor rectangle
spriteBatch.GraphicsDevice.ScissorRectangle = currentScissorRect;

// Restore the RasterizerState
spriteBatch.Begin(rasterizerState: oldState);

So is there no other way? Should I just send the offset to Controls and modify their position? Can't the matrix approach be used for interactable Controls?


texts: How to create a view looking down the sight of the gun

texts:
I am in the midst of creating an FPS game using XNA.  I am using the camera class from the First Person camera demo from dhpoware.com, and everything is working great.  What I'd like to implement is the ability to press the right mouse click and then the view changes so that you look down the gun, like the following image:

I have searched and searched but haven't found anything that will help me out, or at least point me in the right direction.  Can anyone help?


texts: Improving performance of perlin/simplex noise calculations

texts:
I'm using perlin noise to calculate different values for 3d block-world terrain. I calc roughly six (at most) noise values for various terrain features for every 4 blocks in a chunk. The missing values are then filled in by a linear interpolation method. I've built most of this from looking at how existing games like minecraft, terasology, etc do it.

The terrain I've finally wound up with is exactly where I want it - it looks great. However, the game FPS drops heavily any time a new set of chunks are loaded as the player walks.

Each chunk is 16x16x128 blocks. At max settings, the player may have 10 chunks in every direction visible, so if you walk sixteen blocks forward, roughly 10 new chunks are loaded and ten unloaded.

Even with calculating noise for only 1/4 the blocks in a chunk, the performance hit is too much. I've run some profiling and it's the noise calculation method that's the culprit.

Obviously, I need to address this. I just need some advice.

Are there any specific perlin/simplex implementations that are known to be tuned for performance?
Would it be possible/advisable for me to run all of the noise calculations asynchronously and then pass those back to the main thread for actual block-fill and rendering?


texts: Texture coordinates for custom geometry in SceneKit ios9

texts:
I am trying to texture the a custom plane shape I created in scenekit on iOS9. I need the texture to spread out and stretch over the entire surface. I have a vertex and fragment shader on an SCNprogram. But it seems I am doing something wrong and fiddling with this all day, I have come to the conclusion that somehow the Texture coordinates I specify are not correct.

My question is, when creating a geometry, does SceneKit create the texture coordinates automatically so when I specify CGpoint(0,0) for one corner of the texture, it automatically maps it to the bottom left corner of the geometry? Or do I have to manually specify the texture coordinates/uv for the geometry I create?

This problem is a part of a larger question posted here : https://stackoverflow.com/questions/34104369/custom-shader-scnprogram-ios-9-scenekit/34105050#34105050

Please help, I have spent all day tinkering but no success :(


texts: AddForce not moving imported model in Unity

texts:
I've got a Unity project with an imported .fbx model I'm attempting to add movement to.

As a test, I've added a sphere primitive with a sphere collider, a rigid body, and the following script:

public class ball_test : MonoBehaviour {

  private Rigidbody rb;

  void Start ()
    {
    rb = GetComponent<Rigidbody> ();
    }

  void FixedUpdate ()
    {
    Vector3 movement = new Vector3 (1f, 0.0f, 1f);

    rb.AddForce (movement);
    }
  }

This is partly copied from the Roll A Ball tutorial, and this works fine.  The ball slowly rolls with no problem.

I've imported a custom model, added a box collider, a rigid body, and assigned to it the same script.  It doesn't move.

Here's how they're set up:


texts: Verlet rope between two moving points connected with a spring joint?

texts:
I'm connecting two moving rigidbodies using a spring joint in Unity. Between them, a rope will be rendered using a line renderer and I want it to move realistically as the joints move, without physics.
I've read about verlet integration, but only found examples where one point moves, and the other one is calculated, for example a guy with a grappling gun, swinging back and forth.
Here's the current implementation with spring joints.

The second image shows a nice and smooth verlet rope with a line renderer. It's a little too lenient, but looks good. As this doesn't use physics, it doesn't let me move the object or affect the ship, for example if it was stuck on something.

How do I make an elastic rope like the second image, between the spring joints, without the physics engine?


texts:
I'm curently working on a system that make the player character look towards the mouse pointer.
My system is effective but i'm having an issue while displaying the rectangle.

In the Following code i test the mouse position by translating it in the world and then i test if the world pos of the mouse is greater than the position of the player or not. if the mouse is on left side of the boundary, the player will rotate to look at it. To make the rotation, i put the X coordinate on the other side of the position and i make the width negative. THis normaly should emulate the rotation. but my rectangle does not shows up.

Point MousePos = Vector2.Transform(Mouse.GetState().Position.ToVector2(), Matrix.Invert(Camera.GetViewMatrix())).ToPoint;
if (MousePos.X > Position.ToPoint().X)
{
    EntityDisplayRectangle.X = Position.ToPoint().X - (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor / 2;

    EntityDisplayRectangle.Width = (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor;
}else{
    EntityDisplayRectangle.X = Position.ToPoint().X + (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor / 2;

    EntityDisplayRectangle.Width = -((int)EntitySize.X * (int)TileSize.X * _displayResizeFactor);
}
EntityDisplayRectangle.Y = (int)Position.Y - ((int)EntitySize.Y + 1);

here is two screenshots of what i curently have:

the red dot is a point drawn by this line

spriteBatch.DrawPoint(new Vector2(getEntityDisplayRectangle().X, getEntityDisplayRectangle().Y), Color.Red, 3);

So, is there an other way to do or is it even possible?

The player texture is from a tileSet and i use a source rectangle to pick the correct image from it

here is the code that draws the player:

spriteBatch.Draw(TileSet, EntityDisplayRectangle, TileSetOffsetRectangle, Color.White);

Up:

here is the rectangle drawn with a draw rectangle

Note: the red box is the collision box. it's showwn just for debug purpose

it seems that the rectangle struggle to exist when it's width is negative.


texts:
I've been searching a lot for a guide on how to implement 2D animations exported from Spine to Libgdx, but all I could find was outdated tutorials and source codes. I can handle basic Libgdx but Spine seems to be completely different.
I was there, [there](https://esotericsoftware.com/spine-using-runtimes"esoterics software") and also on lots of other sites (low rep level won't let me post more links) but still I've got no idea how to do it.
Does anyone know how to add those animations properly? (doesn't matter if it's json or binary)
Preferably paste some code showing how to display something like spineboy so that I can see exactly what needs to be done. Any other suggestions appreciated..


texts: I am making an angry bird type 2d game using Unity and C#. After I throw the ball from catapult, I have no idea on reloading the ball. Then I use SceneAsync to reload the ball but it is the worst thing I've ever made since I can't make the other sprite objects to continue their movents after the ball is thrown. So what code should I use to reload the balls after throwing?


texts: Normalmap texture in Unity from SP disorted a lot

texts:
As title said, normalmap made from Substance Painter in Unity disorted. Here is the picture:

I made red rectangles to see more cleary. You can see that the some of line of normal were disorted obviously.

I have no Idea why this happens. Model made from Blender 2.78c and exported as FBX. Used Substance Painter 2017.3.3 and tested in Unity 5.6.x and 2017/2018.1.f1.

Any advice will very appreciate it.


texts: how to achieve smooth 360 Degree input with joystick as opposed to 8 angles

texts:
I have been trying to figure out how to implement controller input in my unity project. I figured out a lot of things except for how to take the 360 degree input of a thumbstick and apply that to a transform. I would like smooth movement in whatever degree the thumbstick is currently pushed towards instead of the 8 angle movement(I.E. up, down, left, right, down right, up right, down left, up left).

I have done a lot of research on this topic for a whole day now and have not come up with an answer that I could make sense of or implement correctly. I believe I need to use MathF.Atan2 but I am unsure how to incorporate it correctly.

I currently am in the process of figuring out how to do this and move a UI Image on the canvas to act as a virtual cursor for my controller support.

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

public class JoystickCursor : MonoBehaviour {

public Image cursor;
RectTransform currentPosition;

// Use this for initialization
void Start ()
{

    currentPosition = GetComponent<RectTransform>();
}

// Update is called once per frame
void Update ()
{
    float x = Input.GetAxis("JoymouseX");
    float y = Input.GetAxis("JoymouseY");

    float angle = Mathf.Atan2(x, y);

    if (Input.GetAxis("JoymouseX") > 0)
    {
        currentPosition.localPosition += Vector3.right;
    }

    if (Input.GetAxis("JoymouseX") < 0)
    {
        currentPosition.localPosition += Vector3.left;
    }

    if (Input.GetAxis("JoymouseY") > 0)
    {
        currentPosition.localPosition += Vector3.down;
    }

    if (Input.GetAxis("JoymouseY") < 0)
    {
        currentPosition.localPosition += Vector3.up;
    }

    if (Input.GetAxis("JoymouseX") > 0 && Input.GetAxis("JoymouseY") > 0)
    {
        currentPosition.localPosition += Vector3.right;
        currentPosition.localPosition += Vector3.down;
    }
}
}

As you can see, my current script has not implemented the atan2 portion of it because anywhere I tried has failed to give the correct results. Can anyone help me figure out how to get smooth movement so the user can aim better with the cursor since it is going to act as a crosshair in the game? Any advice is appreciated! Thanks!


texts:
I'm trying to implement basic inelastic ball collision.

The example on the link above is for one dimension. It explains that it's the same for 2D but where the velocities are the components in the direction of the normal in the point of collision. I have tried calculating these components by projecting on the normal vector, and then calculating the new velocities. But then I got stuck. How do I get the new velocity vectors? My attempt below does not produce any good result. Can you help me out? (The two balls are intersecting in one common point when I run the code below)

UPDATE: I have edited the code now so that the two last lines is more correct I think. The thing is I have to combine the new velocity vector component with the old velocity vector component that was first subtracted in the projection operation, to get the complete new velocity vector. Now the animation looks a lot better. I still get occasional ball merging and popping but that could be some other part of my code thats wrong.

var m = this.Mass + other.Mass;
// normal in the point of collision
var n = (this.Position - other.Position).Normalized;
// velocity component perpendicular to the tangent in the point of collision for ball A
var ua = (float)(this.Velocity.Magnitude * Math.Cos(this.Velocity.Angle(n)));
// velocity component perpendicular to the tangent in the point of collision for ball B
var ub = (float)(other.Velocity.Magnitude * Math.Cos(other.Velocity.Angle(n)));
// the new velocity for ball A
var va = (0.9f * other.Mass * (ub - ua) + this.Mass * ua + other.Mass * ub) / m;
// the new velocity for ball B
var vb = (0.9f * this.Mass * (ua - ub) + this.Mass * ua + other.Mass * ub) / m;

// the new velocity vector for ball A
this.Velocity -= n * (ua - va);

// the new velocity vector for ball B
other.Velocity -= n * (ub - vb);


texts:
I am using C++ and SDL and I am trying to get lines with a glowing effect as provided by the image of the game Defcon on the continental outlines.

How could I achieve this glow and blend of the color in 2D? What are some algorithms that I can implement or built in functions that some other graphical frame work has?

I attempted my own solution by rendering lines around the bright center line and reducing its hue but I believe that such method is too expensive in rendering. I need something more efficient.


texts: Not clearing FBO's Texture error in battery economy mode

texts:
When rendering inside a FBO's texture, I'm not using glClear() but overwriting each fragment, GL_BLEND is set to true.
This works just fine, but  I just realised when my laptop switch to economy mode, and I guess switch to egpu (intel 630) , the texture is full of garbage data when drawn.
here you can see first the working render, and then the garbage one. It should be exactly the same the only difference is my laptop is not plugged in AC


texts:
I'm trying to access some variables in my shader, but I think I'm doing this wrong. Say I have a constant buffer that looks like this:

cbuffer perFrame
{
    float foo;
    float bar;
};

I got an ID3D10EffectConstantBuffer reference to it, and I can get a specific index by calling GetMemberByIndex, but how can I figure out how many members perFrame has so that I can get each member without going out of bounds?


texts:
So in an attempt to move out of the console environment I have set up an SFML poject in Visual Studio. I am currently trying to draw a stage from a vector within a vector (Matrix?), and the results are not exactly what I was hoping for.

First i tried mapping out everything as '0's representing empty space, changing the top and bottom vector to '1's, representing objects, thus drawing what essentially would be a rectangle covering the bottom and a rectangle covering the top, everything inbetween ignored.

bool stage::load()
{
 vector<int> tempvec;
 for (int i = 0; i != 30; i++)
 {
    for (int j = 0; j != 40; j++)
    {
        tempvec.push_back(0);
    }
    hitbox.push_back(tempvec);
    tempvec.clear();
 }

 for (int i = 40 - 1; i != -1; i--)
 {
    hitbox[29][i] = 1;
 }
 for (int i = 30 - 1; i != -1; i--)
 {
    hitbox[i][0] = 1;
 }
 return true;    //Will use this more efficently once I get the function to work
}

So this is how I set up the stage variable-wise, hitbox being defined as:

vector <vector<int>> stage::hitbox;

I then try to map out the individual blocks, so every time it finds a '1' in the vector, it should print out a square (quad).

vector<VertexArray> tilesetrender;
VertexArray tmp(Quads, 4);
tmp.resize(4);

level.load();
for (int y = level.hitbox.size() - 1; y >= 0; y--)
{
    for (int x = level.hitbox.at(y).size() - 1; x >= 0; x--)
    {
        switch(level.hitbox[y][x])   //Switch case allows me to expand on this function in the future
            {
            case 1:
                tmp[0].position = Vector2f(y * 20 - 10, x * 20 - 10);
                tmp[1].position = Vector2f(y * 20 - 10, x * 20 + 10);
                tmp[2].position = Vector2f(y * 20 + 10, x * 20 + 10);
                tmp[3].position = Vector2f(y * 20 + 10, x * 20 - 10);
                tilesetrender.push_back(tmp);
            }
    }
}

With all the variables created, I proceed to draw the level.

for (int count = tilesetrender.size() - 1; count >= 0; count--)
{
    renderWindow.draw(tilesetrender.at(count));
}

And what I get is this...

The vertices being white, and the background being red. As I have said, I hoped for drawing two rectangles, one at the top and one at the bottom. I have no real idea regarding what part of my code is causing the error, but I've played around with the position commands the most, to no avail.

Thanks in advance.

EDIT: Code partially corrected (Thanks Alayric), thus rendering this image instead:

White being the vertices, red the background and blue the player (previously not visible).
Although it is a whole lot better, something is still incorrect, as the upper rectangle does not reach all the way, and the lower rectangle does not mirror the upper. I do belive the main problem has been solved, and thus I am able to continue on my own.


texts: How to stop Follow Path steering behavior when reached target?

texts: I'm using libgdx Follow Path Steering Behavior in my top-down game. When unit reaches the end of the path, it goes to the start (not directly, but following path), then to the end and so on. How to stop following path, when unit reached the end point?


texts: Java - Finding distance between player and tile in array

texts:
What is the best way performance wise to do this? When I click a tile I want it to get the distance and if I am close enough I can interact with the tile. One way would be to find the tile by doing mouse / tile width when I click correct? But then how would I get that tiles position? I know how to find the distance I just don't know how to get a certain tiles position from the array when I click it

public void checkDistance(GameContainer gc) {
    Input input = gc.getInput();

    float mouseX = input.getMouseX();
    float mouseY = input.getMouseY();

    double mousetileX = Math.floor(mouseX/tiles.tileWidth);
    double mousetileY = Math.floor(mouseY/tiles.tileHeight);

    //Distance code
    double lengthX = Math.abs(playerX - mousetileX);
    double lengthY = Math.abs(playerY - mousetileY);
    double distance = Math.sqrt((lengthX*lengthX)+(lengthY+lengthY));

    System.out.println(distance);
}


texts: map the section of a procedurally generated surface on a plane

texts:
I'll try to be as clearer as I can.

I have a surface on a 3D space which is not flat, it has hills and depths.

My goal would be intersect it with a plane so that I can map the section of the surface on it.

this is just an example with a tetrahedron, my surface is more complex:

My surface has just a set of vertexes so I was thinking that the solution would be theorically to map the intersection points of line segments bounding each vertex just above the plane with its corresponding one just below.
Then I could connect the points on the plane like if I was drawing triangles on a flat surface.

My concern is also on what structures can I use to achieve this result?
Does XNA give anything that could be of help? I saw the Plane structure and its explaination was quite clear. So next step would be to find the point belonging to a line segment laying on the plane, but sincerly I have no idea on how to proceed.

More than that, I also would like to be able to compute areas of "solid ground" mapped on the plane. But better to face one problem at time.

Hoping I made myself clar, I look forward to any suggestion


texts: Libgdx box2d bodies go through other bodies

texts: I'm  developing a game using libGDX and box2d. I am facing a problem that bodies go through each other... I'm moving the body using a TouchPad by setTransform. I think the problem is that I use setTransform.


texts:
My script for a slot machine isn't working. When the button in the Bilboard GUI is clicked, the below dosen't run. I am new to scripting and this is mostly based on wiki/stack exchange/ Dev page info.

local player = game.Players.LocalPlayer
local textLabel = script.Parent
local toggled = false
local button = script.Parent

textLabel.Text = "Click to Play for 5 Cash!"
slot1Combos = {"Bar", "Seven", "Seven", "Seven", "Cherry", "Cherry", "Cherry", "Cherry", "Orange", "Orange", "Orange", "Orange", "Orange", "Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Banana", "Banana", "Banana", "Banana", "Banana"}
slot2Combos = {"Bar", "Seven", "Cherry", "Cherry", "Cherry", "Orange", "Orange", "Orange", "Orange", "Orange","Orange","Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Banana", "Banana", "Banana", "Banana", "Banana", "Banana"}
slot3Combos = {"Bar", "Seven", "Cherry", "Cherry", "Cherry", "Orange", "Orange", "Orange", "Orange", "Orange","Orange","Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Banana", "Banana", "Banana", "Banana", "Banana", "Banana"}

local function onButtonActivated()
    if toggled == false then
        toggled = true

        x = math.random(1,23)
        y = math.random(1,23)
        z = math.random(1,23)
        g = false
        player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value - 5
        if slot1Combos[math.floor(x)] == "Bar" and slot2Combos[math.floor(y)] == "Bar" and slot3Combos[math.floor(z)] == "Bar" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 60
            textLabel.Text = "You Got 3 Bars. You won 60 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == "Seven" and slot2Combos[math.floor(y)] == "Seven" and slot3Combos[math.floor(z)] == slot2Combos[math.floor(y)] then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 40
            textLabel.Text = "You Got 3 Sevens. You won 40 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == slot2Combos[math.floor(y)] and slot3Combos[math.floor(z)] == slot2Combos[math.floor(y)] then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 10
            textLabel.Text = "You Got 3 of a Kind. You won 10 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"

        elseif slot1Combos[math.floor(x)] == "Cherry" and slot2Combos[math.floor(y)] == "Cherry" and slot3Combos[math.floor(z)] == "Cherry" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 20
            textLabel.Text = "You Got 3 Cherries. You won 20 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == "Cherry" and slot2Combos[math.floor(y)] == "Cherry" or slot3Combos[math.floor(z)] == "Cherry" and slot1Combos[math.floor(x)] == "Cherry" or slot2Combos[math.floor(y)] == "Cherry" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 3
            textLabel.Text = "You Got 2 Cherries. You won 3 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == "Cherry" or  slot2Combos[math.floor(y)] == "Cherry" or  slot3Combos[math.floor(y)] == "Cherry" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 3
            textLabel.Text = "You Got 1 Cherry. You won 3 cash"
        else
            textLabel.Text = "Sorry, you didn't win"
            wait (5)
            textLabel.Text = "Click to Play for 5 Cash!"

        end
    end
button.Activated:Connect(onButtonActivated)
end)

This is the explorer tree with the script highlighted


texts: How to reset the score to 0 when reloading the game?

texts:
My scoring system uses DontDestroyOnLoad to persist between scenes:

public class ScoringSystem : MonoBehaviour {
 private int score = 0;

 public void Correct(int number){
     // If correct add score;
     score = score + number;
 }

 void Start () {
     score = 0;
 }

 void Awake() {
   DontDestroyOnLoad(transform.gameObject);
 }

 public int GetScore(){
     return score;
 }
}

Here is another script that I should include a description about:

  public void iniTag()
 {
     jawab = true;
     Time.timeScale = 0;

         GameObject objek1 = GameObject.FindGameObjectWithTag("Benar1");
         GameObject objek2 = GameObject.FindGameObjectWithTag("Benar2");
         GameObject objek3 = GameObject.FindGameObjectWithTag("Benar3");
         GameObject objek4 = GameObject.FindGameObjectWithTag("Benar4");

         if (objek1.transform.parent.tag == "Jawab4" && objek2.transform.parent.tag == "Jawab3" &&
             objek3.transform.parent.tag == "Jawab2" && objek4.transform.parent.tag == "Jawab1")
         {
             PanelBenar.SetActive(true);
             buttonNext.SetActive(true);
             GameObject.Find("QuizManager").SendMessage("Correct", playerScore);

     }}

     void Start () {
       if (GameObject.Find ("QuizManager") != null) {
         ScoringSystem scoringSystem = GameObject.Find ("QuizManager").GetComponent<ScoringSystem> ();
         gameObject.GetComponent<Text>().text = scoringSystem.GetScore().ToString ();
             } else {
         Debug.Log("No Scoring system found. To test scoring system start from the front page scene");
       }
     }


texts: Seamless tiling with TexturePacker and Marmalade/IwGX

texts:
I'm looking for a way to get seamless tiling working, where the tiles are sprites off a TexturePacker sprite sheet, and the rendering is done with Marmalade's IwGX's streams. I also need to render the tiles in multiple scales at the same time.

Even with TP settings "reduce border artifacts: off" and "inner padding: 0", there are very noticeable, pixel-wide gaps between the tiles. If I move the tiles close together, they look fine at a scale of 1, but anything smaller or larger yields gaps.

If I use one tile per texture, I get no gaps, but it means that I either can't have a variety, or each tile will take one draw call + material switching, which is not only slow, but brings the gaps back.

Any tips?


texts: Where can I find fonts which I can distribute with an open source game?

texts:
I want to be able to release my game as open source, and I need to be able to distribute font files with my game. Where can I find fonts which I can use in this way, and what font licenses should I be looking for?

Are there any further considerations if I want to release my game under GPL rather than a less restrictive open source license such as BSD?

Edit: In response to Olie saying that the question is unclear: My main problem is that fonts which I find on the Internet either do not clearly state their licenses, or have licenses which do not make it clear whether I can distribute the font with software. I know very little about font licenses, but I am looking for sources of fonts which guarantee that the fonts are basically open source / creative commons / public domain / some other font license which allows me to distribute it with a game without paying license fees.


texts: Why in the dialogue system it's showing in the conversation only 2 sentences and not the whole 3 sentences?

texts:
The first script the manager is attached to new empty gameobject:
I want the conversation to start automatic when running the game so i'm calling the method TriggerDialogue in the manager:

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

public class DialogueManager : MonoBehaviour
{
    public DialogueTrigger dialoguetrigger;

    private Queue<string> sentences;

    // Use this for initialization
    void Start ()
    {
        sentences = new Queue<string>();

        dialoguetrigger.TriggerDialogue();
        DisplayNextSentence();
    }

    public void StartDialogue(Dialogue dialogue)
    {
        Debug.Log("Starting conversation with " + dialogue.name);

        sentences.Clear();

        foreach(string sentence in dialogue.sentences)
        {
            sentences.Enqueue(sentence);
        }

        DisplayNextSentence();
    }

    public void DisplayNextSentence()
    {
        if (sentences.Count == 0)
        {
            EndDialogue();
            return;
        }

        string sentence = sentences.Dequeue();
        Debug.Log(sentence);
    }

    void EndDialogue()
    {
        Debug.Log("End of conversation.");
    }
}

Next the DialogueTrigger:

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

public class DialogueTrigger : MonoBehaviour
{
    public Dialogue dialogue;

    public void TriggerDialogue()
    {
        FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
    }
}

Last the Dialogue:

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

[System.Serializable]
public class Dialogue
{
    public string name;

    [TextArea(3, 10)]
    public string[] sentences;
}

In the editor I filled the all 3 TextAreas each one with a sentence.

Hello world

Hi everyone

I have woke up

When running the game it's showing only to the Hi everyone it's not showing the I have woke up.
And it also not showing the "End of conversation." in the log.


texts: Unity is reimporting everything! How do I stop that?

texts:
I have a relatively large project (about 8GB) and it is constantly reimporting itself over and over, to the point that I spend 80% of my time waiting for Unity to:

Reimport everything
Stop hanging.

Even for the smallest of changes (ie. removal of a comment on one line in a script), or changing import settings on an asset can cause these long hangs and reimports.
To make matters worse, this project is also synced over UnityCollabBETA, which throws manual/selective import (auto-refresh is forced on) out the window.
I've also read up that other programs locking asset files (to read them) can also cause Unity to reimport everything as opposed to simply doing a selective import (only reimporting things that has been changed).
I've tried creating blacklists for my auto-backup programs, anti-viruses and anything that would snoop around and/or mess with the Unity Project folders. However, despite those programs not accessing anything, Unity still reimports the whole project every time I alt-tab out.
The only workaround I've found so far is to just kill Unity every time it does it and relaunch it as for some reason it processes the actual changed files first, then hangs itself by going through everything else.
It is also worth noting that I/O is maxed up by Unity (due to the sheer size of the project) and CPU/GPU usage are relatively low (does not exceed 20-30%, assuming nothing else is running in the background).
Note: This has persisted through installs and computers.

Question
How do I stop Unity from reimporting everything without constantly killing Unity?


texts: How can I reduce memory use when implementing an animation in UE4?

texts:
We've already made a tank's track spline animation but it's using a lot of memory because it's implemented inside a tick function. So, it needs to check every second but as you may know it requires a lot of resources if there will be more than 10 tanks..

Is there an optimal solution for this problem? Have others faced these kind of problems?

It would be great if the solution was in blueprints.


texts: A program should take input, process it and give output. So what exactly does a physics engine take as input and provide as output?


texts: How to detect the border of the screen and bounce back?

texts:
if (bucket.x > 0) {
                rect.x += 200 * Gdx.graphics.getDeltaTime();
            }
            if (rect.x < 0) {
                rect.x = 0;
                rect.x += 200 * Gdx.graphics.getDeltaTime();
            }

            if (rect.x > Gdx.app.getGraphics().getWidth() - 30) {
                rect.x -= 200 * Gdx.graphics.getDeltaTime();
            }

I have a rectangle, it has a width of 30 px, I want to move from it's x point till the edge of the screen, when it gets there I want it to go back to the other edge. it's only moving till it hits one edge and it stops.

This might be a basic question but I'm new to Libgdx and I can't find documentation. If I add a while (true ) loop the app would stop working. Basically I want it to move infinitely along the x axis back and forth from right edge to the left edge.

I tried something like

`if (rect.x > 800 - 30) `

it won't work either and I don't like specifying the width of the device explicitly. Basically it's moving but never detecting the right edge of the screen


texts: Finding pitch/yaw values from lookat vector

texts:
I have a camera class that contains a position, a pitch, and a yaw (the pitch and the yaw correspond to y and x rotation values). I want to implement a lookAt function that takes a vector and the function changes the pitch and yaw so it's looking at that point in space. However, I cannot seem to find the math equation to do it (various ones online, none seem to work). How would I be able to implement it?

Here's an example of what I mean:

struct Camera
{
    Vec3 position;
    float pitch, yaw;

    void lookAt(Vec3 center)
    {
        //????
    }

    mat4x4 toTransform() //How I convert the values to a matrix (if this is relevant)
    {
        return CreateLookAtMatrix
            position,
            position + Vec3(cos(pitch)*sin(yaw), sin(pitch), cos(pitch)*cos(yaw)),
            Vec3(0.0f, 1.0f, 0.0f)
            );
    }
}


texts: How to project a 3D circle/ellipse to 2D?

texts:
The 3D ellipse is represented by its center and the vectors for its major and minor axes and the 2D ellipse by its center, the length of the major and minor axes and the angle between the major axis and the x-axis. I need the general projection on an axis-aligned plane, discarding a coordinate.
The problem is that the axes after projection are no longer are aligned to the true axes of the 2D ellipse.


texts: What is the cause of this lighting artifact on my dynamic terrain mesh?

texts:
I am generating my own terrain mesh in Unity, using pseudo-random noise to determine the height. I construct the mesh using quads, each quad is composed of two triangles.

All seems to be going well, except the terrain does not look right - the quads are very visible. You can see the outline of them on the surface, but I haven't seen this effect before elsewhere. I feel that something is wrong with either my normals or my UV's. I am using just one white directional light.

Dynamic Terrain http://www.spannerworx.com/images/terrain.png

I thought the issue was with the normals, so I stopped calling RecalculateNormals and manually calculated the normal for every vertex using the averaged normal of the sum of each triangle touching that vertex. This was a lot of effort, but made no effect and ended up looking just the same.

Has anyone else seen this dynamic mesh effect before and maybe make some suggestions as to how I could try resolve this?

Just to clarify, I am already generating the triangles myself, two per quad. I do it like this:

for (int t = 0; t < quadCount; t++)
{
    int x = t / (Samples - 1);
    int z = t % (Samples - 1);

    // Calculate quad corner indexes
    int indexBR = CalculateIndex(x + 1, z);
    int indexBL = CalculateIndex(x, z);
    int indexTL = CalculateIndex(x, z + 1);
    int indexTR = CalculateIndex(x + 1, z + 1);

    // Assign indexes for triangles
    // Triangle 1
    triangles[6 * t + 0] = indexBR;
    triangles[6 * t + 1] = indexBL;
    triangles[6 * t + 2] = indexTL;

    // Triangle 2
    triangles[6 * t + 3] = indexBR;
    triangles[6 * t + 4] = indexTL;
    triangles[6 * t + 5] = indexTR;

    // Normals stuff...

}


texts: Focus object with specific Rotation in unity C#

texts:
I have different kind of objects with variable dimensions and placed at different position in a scene. I want to focus/display each object with the camera with a hard code rotation (north rotation). Like with specific camera rotation I want to focus the object that it completely show to the camera and center of the screen. For this reason, I have write this code snippet that
1

Get the position behind the specific focus object using
TransformPoint
Provide the elevation using the largest extent of the bound so that it display maximum area of the object.
Assign the position and the fixed rotation

 Vector3 dest = destination.transform.TransformPoint(0, 0, behindPositionDistance);// GetBehindPosition(destination.transform, behindPositionDistance, elevation);
 Debug.Log(dest);
 float eleveMax = Mathf.Max(destination.GetComponent<MeshRenderer>().bounds.extents.x, destination.GetComponent<MeshRenderer>().bounds.extents.z);
 dest = new Vector3(dest.x, eleveMax, dest.z);
 camera.transform.position = dest;
 camera.transform.rotation = lookNorth;

But the problem is, it is not accurately working with all objects as every object is at different position and dimension. I want to focus the full object using the camera but without changing the rotation.


texts: How to give player the ability to toggle visibility of the wall?

texts:
When keyboard 'H' is pressed i want the platformer (wall, roof, floor) become invisible when its visible and become visible when its invisible. Like giving the player ability to control visibility of certain wall so he can pass through it.

This is what i do so far but the wall become blink when i press 'H'. Sometimes the wall become invisible but sometimes it just blink.

public class HideWall : MonoBehaviour {

    public SpriteRenderer wall;
    public Collider2D wallCollider;
    public Effector2D wallEffector;
    private bool visible;

    // Use this for initialization
    void Start () {
        wall = GetComponent<SpriteRenderer> ();
        wallCollider = GetComponent<Collider2D> ();
        wallEffector = GetComponent<Effector2D> ();
        visible = true;
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.H)) {
            wall.enabled = !wall.enabled;
            wallCollider.enabled = !wallCollider.enabled;
            wallEffector.enabled = !wallEffector.enabled;
        }
    }
}


texts:
so, I want to add a Cloth component.
I click on a gameobjects, press “Add Component” in the Inspector search “Cloth”
And nothing comes up.

From my searches in google, nobody had such a problem ever, nor is there any answers.

How can I fix it?
Or reload/reimport the physics components?

Unity version 2019

Thanks in advance!


texts: How do you allow networking code to be written in the later stages of the development?

texts:
I'm currently in the early progress of writing a game which I eventually will want to improve in most aspects.
How can I skip out on writing network code yet leaving it fairly easily implemented, that is, not having to rewrite the entire game just to add it.
What do I have to keep in mind?

I have a component pattern where I separate physics/collision-detection, game logic, data types and animating/rendering from each other.
How do I write a client and server that doesn't have any network code implemented yet can be tested locally?
What should I do in the client and what should I do in the server?
Should I sort of just pretend I have network code finished and send messages between server and client and account for delays etc. even though there will be none?

Edit: It's planned to be a top down RPG. Simple multiplayer where you host a server for your friends is what I'm thinking, so cheating isn't that much of an issue (who would like to play with cheating friends?). Still I'd like to go with a "The server is always right"-approach.

Edit 2: I guess I'm looking for some pointers on what my mind set should be like. How should I handle keyboard input, animating, etc, instead of just applying every effect/change instantly.
Hmmm, I may need to read up properly on networking before going anywhere after all, which was what I had hoped to get away from by making a network skeleton of some sort that could work locally.


texts: 2d character generator for android games

texts: I am a developer, and not an artist. is there a 2d character generator that i can feed one picture and it will generate the proper files to be displayed for a running animation?


texts:
The examples below come from the answer by Steven Stadnicki in Determining Poker Hands

Suppose a player get a hand like A9772. I would like to store the hand as
either 77A92 or, better yet, 7A927. A hand of two pair would be stored with the higher of the two pairs first, then the lower, then the 'kicker' (so, e.g., A9977 would store as 97A97). Three of a kind would be stored with one card of the three first, then the kickers, then the other cards (e.g., A7772 would be 7A277); a full house would be stored with one of its three and then one of its two (e.g., 99777 would be stored as 79779);

How can I do that? Suppose I have a vector of cards :

std::vector<Card> m_cards;

Or simpler a vector of int

std::vector<int> v = {3, 9, 7, 7, 2};

The goal is to sort the above vector as follows: 77932.


texts: How would you draw a tile map with perspective?

texts:
I want the maps in the game I'm working (in Java) to be draw with perspective just to sugar coat it, but I'm not sure how that can be done. If anyone has an article about the math behind it or something similar, that would be greatly appreciated.

Something looking similar to the plain shown on this image found on Google Images:

(not my image, I take no credit)

EDIT: The game is indented to be in 2D, I can draw the map into BufferedImage and then warp it somehow to make it perspective. Just a thought. The real question is, how would the image of the map be warped to to have the angled effect? (Please note, I am trying to avoid using 3D by warping the plain to simulate an angled view)


texts: Can I linear interpolate color along both the X and Y axis of a circle instead of using the distance formula on each individual point?

texts:
I've been unable to make it work and I'm not sure whether it's a problem with my code or if this can even be done. I'm sure there is a way to prove whether it is possible mathematically but I don't know how to approach that either.

I'm trying to do a gradient fill on a circle where the center pixel is BLUE and all points on the edge are RED. Each point within the circle will be a blend of those two colors based on their distance from the center.

Consider this example:

I already have every point along the edge of the circle which I can draw across to fill it. To do a gradient in the southwest quadrant, I thought that I could linear interpolate between A->B to form a gradient and then draw a line C->D starting with RED to the color interpolated between A->B.

Would this be equivalent to using the distance between each point and the origin to linear interpolate the color?

UPDATE

For those interested in seeing what this approximation looks like, I did manage to get it working.

WHITE -> BLACK

RED -> BLUE

The grayscale image is misleading because there are 256 shades of brightness between pure black and pure white and only 127 between any R, G, and B primary colors in 24-bit RGB.

Here is the red/blue image desaturated and adjusted to emphasize how this approximation is drawing the gradient:


texts: How can I rotate models in their local space using OpenGL?

texts:
I have a base application where a model is loaded in, however I need to manipulate the models positions and rotations independently so that each model in the scene can have its own rotation and position.

At the moment, I have only one object and I am trying to combine the rotation, scale and translation matrices to form the model's matrix but for some reason the model is not rendered.

glm::mat4 rotMatrix = eulerAngleXYZ(orientation.x, orientation.y, orientation.z);
glm::mat4 scaleMatrix = scale(mat4(), vec3(1.0f, 1.0f, 1.0f));
glm::mat4 transMatrix = translate(mat4(), vec3(1.0f, 1.0f, 1.0f));

glm::mat4 modelMatrix = transMatrix * rotMatrix * scaleMatrix;

glm::mat4 mvp = camera->getCameraMatrix() * modelMatrix;

glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]);
glUniformMatrix4fv(modelMatrixId, 1, GL_FALSE, &modelMatrix[0][0]);

When using the above code, I don't see anything on the screen, when I'd expect to see the object at position (1.0f, 1.0f, 1.0f) as that is the translation.

When I set the model matrix to glm::mat4(1.0f), I can then see the model correctly but it is placed at the origin and I cannot move it.

What am I doing wrong?