text:
Memory Usage Issue with declared variables (when swapping between states)
So my problem is that When I make a Shader variable and I swap between mainmenustate and gamestate really fast I notice my memory usage increase alot but as soon I switch my Shader varaible into a pointer memory usage dont increase until I put cameraShader = new Shader(); I tried deleting the cameraShader but memory usage still increase
BAREBONE EXAMPLE
#include "glfw.h"
#include "glad.h"
#include "Shader.h"
class State{
private:
Shader* cameraShader;
public:
State(glfwwindow* window, std::stack<State*>* states){

cameraShader("example.vs", "example.fs");
}
virtual ~State(){
delete cameraShader;
}
}
void update(float& dt){
}

void render(){
}

main
  #include "State.h"
  #include "stdafx.h"
  #include "Game.h"

  void Game::framebufferCallback(GLFWwindow* window, int width, int height)
  {
  glViewport(0, 0, width, height);
  }

  Game::Game()
  :previousTime(0.f), dt(0.f)
  {
  //Variables
  const unsigned int width = 854, height = 480;

  //Initiating GLFW Window
  glfwInit();
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  #ifdef _APPLE_
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  #endif

  //Creating a GLFW window
  window = glfwCreateWindow(width, height, "EXAMPLE", NULL, NULL);

  //Checking if Window was initiated
  if (window == NULL) {
    std::cout << "GLFW FAILED TO INITIATE WINDOW!\n";
    glfwTerminate();
    }

  glfwMakeContextCurrent(window);

  //Setting Window's aspect ratio
  glfwSetWindowAspectRatio(window, 16, 9);

  //Centering Window
  int windowWidth, windowHeight;
  glfwGetWindowSize(window, &windowWidth, &windowHeight);
  const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
  glfwSetWindowPos(window, mode->width / 2 - windowWidth / 2, mode->height /
  2 - windowHeight / 2);

  //Checking if Glad was initiated
  if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    std::cout << "GLAD FAILED TO BE INITIATED\n";
    }

  //Enabling OpenGl features
  glEnable(GL_CULL_FACE);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
  glEnable(GL_STENCIL_TEST);
  glEnable(GL_DEPTH_TEST);

  stbi_set_flip_vertically_on_load(true);
  //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

 //Setting-Up Viewport
 glfwSetFramebufferSizeCallback(window, framebufferCallback);

//Intitiating MainMenu
 states.push(new MainMenuState(window, &states));
 }

 Game::~Game()
{
}

int Game::glfwGetWindowShouldClose()
{
return glfwWindowShouldClose(window);
}

void Game::processWindowEvents()
{
//Calculating Deltatime
double currentTime = glfwGetTime();
dt = currentTime - previousTime;
previousTime = currentTime;
}

void Game::update()
{
processWindowEvents();
if (!states.empty()) {

    states.top()->update(dt);
    if (states.top()->getQuit()) {
        states.top()->endstate();
        delete states.top();
        states.pop();
        std::cout << "States has been deleted\n";
    }
}
else {
    glfwSetWindowShouldClose(window, GL_TRUE);
}
}

void Game::render()
{
//Clearing display
glClearColor(0.15f, .45f, .60f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

if (!states.empty()) {
    states.top()->render();
}

glfwSwapBuffers(window);
glfwPollEvents();
}

Shader class
#ifndef SHADER_H
#define SHADER_H

#include <glad/glad.h>
#include <glm/glm.hpp>

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

class Shader
 {
  public:
 unsigned int ID;

 Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath = nullptr)
 {
    // 1. retrieve the vertex/fragment source code from filePath
    std::string vertexCode;
    std::string fragmentCode;
    std::string geometryCode;
    std::ifstream vShaderFile;
    std::ifstream fShaderFile;
    std::ifstream gShaderFile;
    // ensure ifstream objects can throw exceptions:
    vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
    fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
    gShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
    try
    {
        // open files
        vShaderFile.open(vertexPath);
        fShaderFile.open(fragmentPath);
        std::stringstream vShaderStream, fShaderStream;
        // read file's buffer contents into streams
        vShaderStream << vShaderFile.rdbuf();
        fShaderStream << fShaderFile.rdbuf();
        // close file handlers
        vShaderFile.close();
        fShaderFile.close();
        // convert stream into string
        vertexCode = vShaderStream.str();
        fragmentCode = fShaderStream.str();
        // if geometry shader path is present, also load a geometry shader
        if(geometryPath != nullptr)
        {
            gShaderFile.open(geometryPath);
            std::stringstream gShaderStream;
            gShaderStream << gShaderFile.rdbuf();
            gShaderFile.close();
            geometryCode = gShaderStream.str();
        }
    }
    catch (std::ifstream::failure& e)
    {
        std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
    }
    const char* vShaderCode = vertexCode.c_str();
    const char * fShaderCode = fragmentCode.c_str();
    // 2. compile shaders
    unsigned int vertex, fragment;
    // vertex shader
    vertex = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex, 1, &vShaderCode, NULL);
    glCompileShader(vertex);
    checkCompileErrors(vertex, "VERTEX");
    // fragment Shader
    fragment = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment, 1, &fShaderCode, NULL);
    glCompileShader(fragment);
    checkCompileErrors(fragment, "FRAGMENT");
    // if geometry shader is given, compile geometry shader
    unsigned int geometry;
    if(geometryPath != nullptr)
    {
        const char * gShaderCode = geometryCode.c_str();
        geometry = glCreateShader(GL_GEOMETRY_SHADER);
        glShaderSource(geometry, 1, &gShaderCode, NULL);
        glCompileShader(geometry);
        checkCompileErrors(geometry, "GEOMETRY");
    }
    // shader Program
    ID = glCreateProgram();
    glAttachShader(ID, vertex);
    glAttachShader(ID, fragment);
    if(geometryPath != nullptr)
        glAttachShader(ID, geometry);
    glLinkProgram(ID);
    checkCompileErrors(ID, "PROGRAM");
    // delete the shaders as they're linked into our program now and no longer necessery
    glDeleteShader(vertex);
    glDeleteShader(fragment);
    if(geometryPath != nullptr)
        glDeleteShader(geometry);

}
// activate the shader
// ------------------------------------------------------------------------
void use()
{
    glUseProgram(ID);
}
// utility uniform functions
// ------------------------------------------------------------------------
void setBool(const std::string &name, bool value) const
{
    glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
// ------------------------------------------------------------------------
void setInt(const std::string &name, int value) const
{
    glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
// ------------------------------------------------------------------------
void setFloat(const std::string &name, float value) const
{
    glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
// ------------------------------------------------------------------------
void setVec2(const std::string &name, const glm::vec2 &value) const
{
    glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec2(const std::string &name, float x, float y) const
{
    glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y);
}
// ------------------------------------------------------------------------
void setVec3(const std::string &name, const glm::vec3 &value) const
{
    glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec3(const std::string &name, float x, float y, float z) const
{
    glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
}
// ------------------------------------------------------------------------
void setVec4(const std::string &name, const glm::vec4 &value) const
{
    glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec4(const std::string &name, float x, float y, float z, float w)
{
    glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w);
}
// ------------------------------------------------------------------------
void setMat2(const std::string &name, const glm::mat2 &mat) const
{
    glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
// ------------------------------------------------------------------------
void setMat3(const std::string &name, const glm::mat3 &mat) const
{
    glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
// ------------------------------------------------------------------------
void setMat4(const std::string &name, const glm::mat4 &mat) const
{
    glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}

private:
// utility function for checking shader compilation/linking errors.
// ------------------------------------------------------------------------
void checkCompileErrors(GLuint shader, std::string type)
{
    GLint success;
    GLchar infoLog[1024];
    if(type != "PROGRAM")
    {
        glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
        if(!success)
        {
            glGetShaderInfoLog(shader, 1024, NULL, infoLog);
            std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog;
        }
    }
    else
    {
        glGetProgramiv(shader, GL_LINK_STATUS, &success);
        if(!success)
        {
            glGetProgramInfoLog(shader, 1024, NULL, infoLog);
            std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog;
        }
    }
}
};
    #endif

Could it be that your Shader class is missing a dtor with a call to glDeleteProgram?

Shader need a:

Copy constructor
Move constructor
Copy assignment operator
Move assignment operator
Destructor

For stop leak videocard memory.
You call glCreateXxxx and you should call glDeleteXxxx on destruction.
https://khronos.org/registry/OpenGL-Refpages/gl4/


text:
How to get last 20 banned Steam IDs
I am working on a cheat analysis system using data from Steam. From this page, we can get the last 20 checked Steam IDs. Is there a way to get the last 20 banned Steam IDs?
VacList has a section with the last banned accounts, but I don't know how to extract the data. A solution like that provided by vacbanned.com would be much better.

According to the information posted on the Steam Web API, Steam doesn't provide a way to get the last 20 banned Steam IDs.
GetPlayerBans takes a comma-delimited list of SteamIDs as input & returns the  Community, VAC, and Economy ban statuses for given players of the SteamIDs.
Based on that, I suspect the listings you mentioned are aggregates of data they've pulled from Steam. For example, they might be listing the last 20 banned accounts out of all the accounts they've checked. Or the 20 bans they've found that where most recently enacted.
You might be able to get the data from one of the other sites you've mentioned, but I didn't see any APIs provided by either VacList or Vacbanned. You could contact them to see if they would be willing to share that information.
Automating the extraction of their content (scraping) and the legality thereof, isn't something I feel qualified to speak about beyond noting that it isn't on topic for game dev.

Thanks for your reply and for your checks! I'll dig some more ;-)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Having trouble with 2d projection (Opengl)
I need to change the normalize coords from -1 to 1 to the width and height of my application. The reason why I want to change the normalize coords is because i think it would be a easier set position of objects and find the globalbounds of objects
my Rectangle disappear when i put my projection matrix in the vertex shader
Vertex shader code
#version 330

layout(location = 0) in vec4 position;
uniform vec2 offset;
uniform mat4 projection;

void main()
{
 vec4 translate = vec4(offset.x, offset.y, 0.0, 0.0); //Using translate to move the rectangle via
                                                      //gluniform2f
 gl_Position = projection * position + translate;
}

glm::mat4 proj = glm::ortho(-2.f, 2.f, -1.5f, 1.5f, -1.f, 1.f);
shader.setMat4("proj", proj);

There's no matrix named "proj" in your shader. On the cpu side, in the setMat4() function call, change the first argument "proj" to "projection".

@Daniel_1985 thankyou so much

Did it solve the problem?

@Daniel_1985 yes it did but i notice my rectangle is still has a -1 to 1 position even its drawing it as my height and width of my application

@Daniel_1985 .What im basically trying to ask does the projection actually changes the normalize coords or just manipulates the ortho to fit the -1 to 1 coords

You're correct on that the projection manipulates the ortho to fit the (-1 to1) coords. The glm::ortho() function basically creates an orthographic transformation matrix that transforms vertices from view/camera space into clip space (-1 to 1).

You can learn more about the various transformation stages here: https://learnopengl.com/Getting-started/Coordinate-Systems

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Unity character customization parts
I'm relatively new to unity, started a couple weeks ago and so far I managed to setup a character with multiple parts, like hair, head, and body. Here's how it looks like:

I also managed to import some animation thanks to https://www.mixamo.com/ and everything works perfectly well; for now...
Now, I'm struggling with the "change" part mecanism. I'd like to swap the "nude" body mesh part, to an "armor" mesh or any other body mesh. Problem is, when I change the model in the SkinnedMeshRenderer it tells me the following:

with this result:

I did some reseach about this error message, and it actually makes sense, the given mesh doesn't have any bone setup, bone weights or such.
I would like to know if it's possible to use "common" skeleton for every models and assign it throught code?

It is possible, but for any part that needs to deform (like bending arms and legs), all your substitute meshes have to have skinning weights set to work with the same skeleton as your base mesh.

Thanks for your comment. Do you think it's possible to assign the weights to my mesh using the base mesh bone weights then?

Anything computable is possible, but that sounds like probably not what you want. Especially if you have hard armor pieces, you'll want to weight them differently so that a metal plate doesn't bend in the middle the way a cloth sleeve does.

I understand what you mean. The models i'm using are single pieces and don't have this type of constraints. I'm going to look the Unity API to see how I can set bone weights to my mesh.

Did you consider simply parenting these rigid pieces to the bone transforms, then?

Not sure to know how to parent the rigid model parts to the bone transforms, but I did a script that "copies" the bindposes from the original model to my target part, but it doesn't seem to work, since the model doesn't show up on play mode. Do you have any hints on how I can achieve it?


text:
Find format of data from Steam API using Python
I have some user data downloaded using the Steam API (I am following the approach described here) and I need to find the format for each entry of the CSV file I generated (available here).
Using Python, the solution I came up with is the following:
import pandas as pd
import sys

df1 = pd.read_csv("./data/csgo_cheater_data_01_14_21_full.csv")
for ii in range(189):
    print(df1.columns[ii], type(df1[df1.columns[ii]].values[0]))

Running this snipped, the result is that most variables are float64, plus a few int64. Does it make sense? Is this the real format of the data or are they somehow converted when retrieved using the API?

Since you can open csv in any text editor and the first line give you somelike total_of_x, numeric values do make sense

Have you found any specific variables that don't look like they make sense in the format your code reads them currently? A concrete example can help focus answers. Or, if all the variables make sense to you in their current format, then what is the problem to solve?


text:
Best way to save screenshots in a game?
I'm making a game, and I'm adding a screenshots feature. Currently I save screenshot files to <Home Directory>/Pictures/MyGame/. However, I'm not sure if these files will be accessible on Mobile. On Mobile, I want to save them to the gallery. What's the best way to save screenshots in my game? I am not using a game engine, so using any cross-platform helper functions is completely out of the question. I only have access to built-in libraries like Cocoa on MacOS.

By mobile, do you mean iOS, Android, or both? Are you using any particular engine or library to build your game that might have some cross-platform helpers for this built-in?

@DMGregory I'm going to be developing for iOS first, but ultimately I mean first. I'm using plain C and C++ mostly, and I do have access to built-in libraries like Cocoa. So about engines that have cross-platform helpers, the answer is no. Should I edit this info into the question?

Yes please. Use the tags for your target platforms too.

@DMGregory I don't think I can include all the platforms due to the 5 tag limit

Have you checked what environment variables exist? There seems to be support to get environment variables in std namespace.

@Emil You mean getenv()? Is there a place I can research environment variables?

@user147292 I can barely use a mac keyboard and you ask me haha :-) I guess maybe apple has some documentation somewhere? Maybe inside XCode?


text:
stop object while falling

The object have forwardForce.
using UnityEngine;

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

    }

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

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

you want to reset the level, teleport the player back on the track or just stop the camera from following? can your player jump (or is a simple ground check enough to determinate if he fell off).

@Zibelas No! I don't wanna reset. Look while the object is falling the z axis increasing which means the object is traveling through z axis. I want not to change the z axis the object is falling.

You can lock the axis to prevent rotation

@Zibelas Sorry! I am new to game development. I couldn't get you. How to lock the axis?

Take a look at the constraint properties of the rigidbody of your object

@Zibelas I froze z axis but, the object isn't moving anymore.

Let us continue this discussion in chat.

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce=1000f;

    void FixedUpdate()
    {
        rb.AddForce(0,0,forwardForce * Time.deltaTime);
        if(Input.GetKey("d")){
            rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }else if(Input.GetKey("a")){
            rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }
        if(Physics.Raycast(transform.position,Vector3.down,0.5f)==false){
            rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, 0);
        }else{

        }
    }
}

I tried by detecting the player is onGrounded or not. Then, I set velocity = 0 if player isn't grounded
Thanks Zibelas


text:
Refresh UI after changing source code
I was trying following things.
GameManager :
bool gameHasEnded = false;
public GameObject completeLevelUI;

public void CompleteLevel(){
    completeLevelUI.SetActive(true);
}

public void EndGame(){
    if(gameHasEnded == false){
        gameHasEnded = true;
        Invoke("Restart",2f);
    }
}

void Restart(){
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

EndTrigger :
public GameManager gameManager;

void OnTriggerEnter(){
    gameManager.CompleteLevel();
}

I get a log in the console "END". Earlier I was using Console.Log("END"); on CompleteLevel(), but I changed that source code. The old code seems to be working and not the new one. It's like Unity couldn't refresh that source code. (And I am sure that I have successfully saved the C# file.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCollision : MonoBehaviour
{

    public PlayerMovement movement;

    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log(collisionInfo.collider.name);
        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;
            FindObjectOfType<GameManager>().EndGame();
        }
    }

}
```

Hi there, silly question maybe, but since your old code code is still executed, but you made sure to save the C# file, did you restart the game by exiting play mode and re-entering it?

@D.Kallan Yes! I did. I tried twice times

What is calling EndGame? Something in your UI? Is your GameManager getting destroyed on Scene reload or is something resetting gameHasEnded back to true? Are you sure the END is not coming from a different script? Like the one that prints ground

@Zibelas Yes! You were right. When I double clicked the END log then, it returned me to PlayerCollision.

I had solved the problem another way. I added another source code to PlayerCollision if collisionInfo name is END than it will call an function from GameManager which is CompleteLevel. I solved the problem another way. But, I want to access EndTrigger without that source code. Why I am unable to access EndTrigger?

because it uses the wrong method OnTriggerEnter() is missing the parameter of the collision OnTriggerEnter(Collider other). If is has not the parameter, Unity is not calling it on a collision since it can not magically know that it should use it for collision

@Zibelas Thanks

As Zibelas said in the comments, you are using the incorrect method in OnTriggerEnter(). By not adding anything into the parentheses, the program doesn't know when it should activate the method, thus causing it not to do anything, because it isn't being called. In order to fix this, simply replace OnTriggerEnter() with OnTriggerEnter(Collider other). This will tell it when to run the method.


text:
objects are keep falling

I added some screenshots above. When I run the game obstacle are falling rapidly through y axis. So, there's no more obstacle in that ground. If there's ground than those obstacle should stopped. I tried by freezing them. But, when another object hit them they are froze. So, I want ground to stop them. I have another question also. I have player movement. When I will run the program. The Player should be go through z axis. But, The object(player) don't move.
PlayerMovement.cs
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce=2000f;

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

        if(!Input.touchSupported)
        {
            // Still support PC keys
            if(Input.GetKey(KeyCode.D))
            {
                rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
            }
            else if(Input.GetKey(KeyCode.A))
            {
                rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
            }
        }
        else
        {
            // For touch devices
            if(Input.touchCount == 1)
            {
                var touch = Input.GetTouch(0);
                var touchPos = touch.position;

                var isRight = touchPos.x >= Screen.width / 2f;

                if(isRight)
                {
                    rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
                }
                else
                {
                    rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
                }
            }
        }

        if(Physics.Raycast(transform.position,Vector3.down,0.5f)==false){
            // rb.velocity = new Vector3(0, rb.velocity.y, 0);
            rb.constraints = RigidbodyConstraints.FreezePositionZ;
        }else{
            rb.constraints = RigidbodyConstraints.None;
        }

        if(rb.position.y < -1f){
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

PlayerCollision.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerCollision : MonoBehaviour
{

    public PlayerMovement movement;

    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log(collisionInfo.collider.name);
        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;
            FindObjectOfType<GameManager>().EndGame();
        }else if(collisionInfo.collider.name == "END"){
            FindObjectOfType<GameManager>().CompleteLevel();
        }
    }
    void Restart(){
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

If you look at above source code clearly. So, you might see that I have a Debug.Log right there. But, when I run the game. I don't get any message to console.
As a new game developer(learning) I don't know what's happening, what's wrong with this.

This looks like you're still solving the same problem as your previous question. Instead of posting a new question, please edit the existing question to focus on the problem as you now understand it thanks to your troubleshooting. Be sure to show us your physics layer settings. Do not pack two questions into one post.

@DMGregory OK! I understood why you closed it..... :)


text:
Why would I want to set a minimal OpenGL version before creating the context?
Typical GLFW applications have these lines after glfwInit():
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

And similarly:
glfwMakeContextCurrent(window);

I get that glfwMakeContextCurrent is needed before sending calls to the OpenGL API, but the doc says

You can require a minimum OpenGL version by setting the GLFW_CONTEXT_VERSION_MAJOR and GLFW_CONTEXT_VERSION_MINOR hints before creation

But why would I want that? Why would I cut options for OpenGL versions? I did not understand that, if I am interpreting it correctly in the first place

Like many others, OpenGL is an evolving software. As time goes by, it needs to adapt to users needs and to the new and evolving hardware that the manufacturers such as Nvidia come up with.
As OpenGL version goes up, new features are offered, since sometimes those features require a more recent hardware, not every user can benefit from them. So this means that a shiny new thing you can do with OpenGL and show your players in your game will not be available for the users using older hardware.
By setting the minimal version of OpenGL, you're telling the API that you'll probably use more recent features, and it will help tell whether the user can run your game or not. It will also prevent the use of some older, deprecated features.
One of the side effects I can think of, is that software like NVIDIA Nsight will support calls only for the most recent OpenGL versions. So if you decide to build your game supporting an older OpenGL minimal version (because you want to support more users), you'll not be able that kind of tool to debug your code.
From what I understand, studios that have more resources will implement the same feature in a similar way using multiple OpenGL version, where the "more recent" way will be more beautiful and/or run faster.

You want to set a minimum version to have a functionality of that version available. That includes functionality of the shading language of the respective version.
Examples:

Set 4.0 to have tessellation in the shader pipeline
Set 4.2 to have a debug context
Set 4.5 to have DSA (Direct State Access) available

... and so on.
See also: https://www.khronos.org/opengl/wiki/OpenGL_Context
and https://www.glfw.org/docs/latest/context_guide.html
The latest version, 4.6, was defined in 2017. Setting a minimum versions may give the driver opportunities to optimise and to not reserve resources for functionality that will not be used, but that's speculative from my side.


text:
How to Make Border of 2D Game in Unity

I have a border by default. But, I'm having trouble detecting if my object collides with the border. I am looking for efficient ways to do this, and I am not sure what should I use. I thought using a Tilemap might work. But, it was only giving me a grid, not a Tilemap. Even then, I was unable to figure out how to use the grid.
How should I go about creating this?

If you want "2D" objects to "Collide" then presumably you looked into the "Collider2D" components available in the engine? What have you tried based on your research so far?

@DMGregory I have added a Sprite Shape. I am able to detect collision. But, I have a question. When I increase/decrease resolution(screen size) those Sprite Shape goes away... Like I am unable to look at them...

There are like 10 different ways to move objects in Unity. And how to limit that movement would depend on which one you choose. Can you tell us more about how you are moving that square? By changing transform.position? Or by calling the method rigidbody.AddForce?

Regarding your question about your sprite disappearing when you change the screen resolution: That seems unrelated to the question you are asking here, so you should post it as a separate question.

As far as I can understand, you are trying to stop the player from moving out of the border. I would recommend doing this by using a Tilemap and adding a Tilemap Collider to the Grid inside the Tilemap GameObject. Then, simply just create a tile palette and add the chosen image for the border. Then, you can "draw" with the tile painter in the Palette Window. Also, by doing this, you can easily expand or shrink the border while developing, just by using the Palette Tools. You will also want to make sure you have the IsTrigger button unticked in the Grid Properties.

You can do it such as suggested in the comment section (using tilemap collision) or you can do it programmatically:
if (playerX >= borderX && playerX <= borderX + borderWidth &&
    playerY >= borderY && playerY <= borderY + borderHeight)
   you touch a border
else
   player move

I used Sprite and added OnCollisionEnter2D.
void OnCollisionEnter2D(Collision2D collision){
    if(collision.collider.tag =="obstacle"){
       Debug.Log("Finish");
    }
}

This way I am able to detect collision.

In the question you stated that the tilemap didnt work out for you (at first?). Did you just add a tilemap and this function and that made it work? Or did you do anything else? (What is different here from what you did when you wrote the question?)


text:
Do game testers have to live locally to be considered?
I've been told by a few former game testers that you must live in their city because game testing has few educational requirements so it's easier to hire someone local. Some descriptions say "you must live in or near (insert city)". Some won't tell you this until you get on the phone with them.

It sounds to me like you correctly understand that each different employer has their own hiring requirements which might differ, and that hiring locally is one common requirement that many studios have. The only way to know whether a studio you're interested in working for has this requirement is to check their published listings, or talk to them, as you've done. What are you looking for from an answer, beyond this?

I live in an area where there are a only few game tester jobs. I don't want to waste my time applying out of state if I can only apply in my city. That's why I asked this.

We cannot speak on behalf of all of those out-of-state companies. Based on your research, it sounds like you've already identified that those employers are also likely to prefer to hire QC who live nearby. So I don't expect anything we say here would tell you anything you don't already know.

It depends entirely on the situation.
There are a number of factors that favor hiring locally:

You have the option of person to person interviews.
Hiring across state lines can require additional considerations with respect to things like taxes, withholding and worker's compensation insurance.
It's easier to secure your game from various leaks. In person testers can talk about your game, but it's much harder for them to leak footage or files.
Some testing include observing the testers as the play and it's much easier to do this if they are physically present.
Typically, the number of applicants exceeds the number of positions; hiring locally restricts the number of applicants that need to be reviewed.

Some situation favor or possibly even require hiring remotely:

Assessing network performance under conditions that more closely resemble expected  post-release play.
Testing the game with demographics that aren't present or under represented locally.

Ultimately a smart company is going to tune their hiring process based on their needs and resources.

Regarding network performance testing: I asked a question a couple years ago: How can I simulate a bad internet connection for testing purposes?


text:
How to add time delay in Unity C#
So I'm trying to make a camera zoom in, but Thread.Sleep doesn't work.
Here is the code:
    void Start() {
    for (int a = 0; a > 1000; a = a + 1)
    {
        Debug.Log("Done!");
        Thread.Sleep(100);
    }
}

The error code is this:
Assets\StartScene\CamScript.cs(12,13): error CS0103: The name 'Thread' does not exist in the current context

You are getting this error message because  you are missing a line that accesses the API for this. Simply add using System.Threading; at the top of your script. This will access the API for it. Or use a coroutine, which won’t freeze the entire game as a whole and is a much better alternative, as DMGregory suggested.

using System.Threading; will remove the compiler error, but replace it with a stall, where the game as a whole freezes for a tenth of a second. Not exactly ideal in this context.

@DMGregory I know, that’s why I said your answer is better. But, I was just trying to help.

Sorry but I dont think this should be the answer (it's the OP's choice, but) seeing as it would make people think they can use T.Sleep to add delays. And I just see the same answer as DMGregory's but much shorter (the word coroutine). You dont really say his answer is better.. nor that T.Sleep shouldnt be used. Your answer reads as: "better than Sleep, use a coroutine" which has a different meaning.

@D.Kallan I know. I want to remove it, because DMGregory’s answer is much better.

You want a Coroutine.
// IEnumerator tells Unity to run this as a coroutine
// that can suspend and wait, without stalling the whole game.
IEnumerator Start() {
    // Your loop condition was backwards,
    // so it would never execute the body.
    // It looks like you want a < here instead.
    for (int a = 0; a < 1000; a++)
    {
        Debug.Log("Done!");
        // yield return means "suspend this method"
        // and the WaitForSeconds tells us when to resume it.
        yield return new WaitForSeconds(0.1f);
    }
}

An important thing to understand about Unity is that the MonoBehaviour message methods like Start() and Update() are called on the main thread (ie. single-threaded). So if you stall one of them by hitting a long-running loop or sleeping the thread, you cause the entire game to hang.
So, if you want to add a delay, it needs to be by yielding control back to the engine temporarily  - so it can continue running other update functions, accepting input, rendering frames, etc. - until you are ready to resume your work.


text:
Main Camera re-sizing in 2d
My UI :

An UI from YouTube video :

Look my camera's size is 10 and his camera's size is only 5. But, my camera's width is larger than height. If you look at scale (x,y,z)=(1,1,1). I tried to change them. But, nothing changes.I tried to change ViewPort Rect then, I am able to change the size of Main Camera. But, look at following image. His ViewPort Rect is 1 by 1 mine also. But, we have differences of width and height.
How to fix it?

While D.Kallan focuses with his answer on how to make it closer to Brackeys', this answer focuses more on if you actually should do that.
Since you are new to GameDev, I would guess for now most of your projects are for yourself and the learning experience. Instead of following the tutorial to the letter, you should make the game look great on your own platform. Since the topic of handling different resolutions, fit to the screen and similar can be quite confusing (even more so when you try to learn the basics), you should fix your game to the resolution you are actually using yourself.
That means, if you plan to make a small mobile game, use a fixed aspect and enter your own mobile resolution there. If it is for pc, use your screen resolution under which you plan to play the game later. This saves you the trouble that while the game will work and looks similar to the tutorial in the editor, it might look totally different when you want to play your own game or show it to friends. Once the game is actually done and looks great on your own hardware, you can learn about the topics on how to make it look great for everybody else.
You can set a fixed resolution in the game tab.

I have noticed that when your camera is on Free Aspect, the size changes with the size of your game window.
If you compare the differences between your UI and Brackeys' UI, you see that your game window is wider than his, and a little smaller vertically.
Try resizing the game window to match his and your camera should then match about the same ratio as Brackeys' has.


text:
What is the proper way to create a camera matrix?
I am having issues when trying to create a camera transform. It seems to have odd distortions and it does not seem to rotate properly, though it will translate alright. While I have seen issues like this where the rotation does not work, I have not found any like my issue.
This is what I currently do to create the matrix:
Mat4 TransformLookAt(Vec3 from, Vec3 to, Vec3 world_up) {
    Mat4 view_matrix = Mat4New(1.0f);
    Mat4 rot_matrix = Mat4New(1.0f);

    Vec3 axis_n = Vec3Normalise(Vec3Subtract(to, from));
    Vec3 axis_v = Vec3Normalise(Vec3Cross(from, Vec3Cross(world_up, from)));
    Vec3 axis_u = Vec3Normalise(Vec3Cross(axis_n, axis_v));

    // Rotate on the X-axis
    rot_matrix.ax = axis_u.x;
    rot_matrix.ay = axis_u.y;
    rot_matrix.az = axis_u.z;

    // Rotate on the Y-axis
    rot_matrix.bx = axis_v.x;
    rot_matrix.by = axis_v.y;
    rot_matrix.bz = axis_v.z;

    // Rotate on the Z-axis
    rot_matrix.cx = axis_n.x;
    rot_matrix.cy = axis_n.y;
    rot_matrix.cz = axis_n.z;

    // Translate the camera
    view_matrix.aw = -from.x;
    view_matrix.bw = -from.y;
    view_matrix.cw = -from.z;

    view_matrix = Mat4ByMat4Multiply(view_matrix, rot_matrix);

    return view_matrix;
}

The camera is at (1.0, 0.0, 3.0) at is set to look at (0.0, 0.0, 0.0), which is where the centre of the cube is located. Here is what it looks like:

I would expect to see the left side and possibly top of the cube (since that is what this is supposed to do), but instead the cube has been distorted so that its left side cannot be seen.
That leads me to this question: If none of the methods like the one I've tried to implement works, then what is the proper way to create a camera matrix? What am I missing so that this does not work?
I understand how it should work, but I just can't get it to work. I feel like it might be something obvious, but I can't seem to figure it out.

// Rotate on the X-axis
these comments are really misleading, what you are doing is setting what the 'local' versions of these axes are in 'global' coordinates
Vec3 axis_v = Vec3Normalise(Vec3Cross(from, Vec3Cross(world_up, from))); this is confusing too - shouldn't 'from' be 'axis_n'?

I recommend that you try GLM for your math library. Here is some sample code from my camera class -- https://github.com/sjhalayka/opengl4_stlview/blob/6ea4b942a8a5b40f923f5cd99da0cdec5e06e0e4/uv_camera.cpp#L48
Until you switch to GLM, here is another code for your reference:
// https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml
// https://www.opengl.org/sdk/docs/man2/xhtml/gluLookAt.xml

void multiply_4x4_matrices(float (&in_a)[16], float (&in_b)[16], float (&out)[16])
{
    //   matrix layout:
    //
    //   [0 4  8 12]
    //   [1 5  9 13]
    //   [2 6 10 14]
    //   [3 7 11 15]

    out[0] = in_a[0] * in_b[0] + in_a[4] * in_b[1] + in_a[8] * in_b[2] + in_a[12] * in_b[3];
    out[1] = in_a[1] * in_b[0] + in_a[5] * in_b[1] + in_a[9] * in_b[2] + in_a[13] * in_b[3];
    out[2] = in_a[2] * in_b[0] + in_a[6] * in_b[1] + in_a[10] * in_b[2] + in_a[14] * in_b[3];
    out[3] = in_a[3] * in_b[0] + in_a[7] * in_b[1] + in_a[11] * in_b[2] + in_a[15] * in_b[3];
    out[4] = in_a[0] * in_b[4] + in_a[4] * in_b[5] + in_a[8] * in_b[6] + in_a[12] * in_b[7];
    out[5] = in_a[1] * in_b[4] + in_a[5] * in_b[5] + in_a[9] * in_b[6] + in_a[13] * in_b[7];
    out[6] = in_a[2] * in_b[4] + in_a[6] * in_b[5] + in_a[10] * in_b[6] + in_a[14] * in_b[7];
    out[7] = in_a[3] * in_b[4] + in_a[7] * in_b[5] + in_a[11] * in_b[6] + in_a[15] * in_b[7];
    out[8] = in_a[0] * in_b[8] + in_a[4] * in_b[9] + in_a[8] * in_b[10] + in_a[12] * in_b[11];
    out[9] = in_a[1] * in_b[8] + in_a[5] * in_b[9] + in_a[9] * in_b[10] + in_a[13] * in_b[11];
    out[10] = in_a[2] * in_b[8] + in_a[6] * in_b[9] + in_a[10] * in_b[10] + in_a[14] * in_b[11];
    out[11] = in_a[3] * in_b[8] + in_a[7] * in_b[9] + in_a[11] * in_b[10] + in_a[15] * in_b[11];
    out[12] = in_a[0] * in_b[12] + in_a[4] * in_b[13] + in_a[8] * in_b[14] + in_a[12] * in_b[15];
    out[13] = in_a[1] * in_b[12] + in_a[5] * in_b[13] + in_a[9] * in_b[14] + in_a[13] * in_b[15];
    out[14] = in_a[2] * in_b[12] + in_a[6] * in_b[13] + in_a[10] * in_b[14] + in_a[14] * in_b[15];
    out[15] = in_a[3] * in_b[12] + in_a[7] * in_b[13] + in_a[11] * in_b[14] + in_a[15] * in_b[15];
}

// centre is the look at position
void init_perspective_camera(float fovy, float aspect, float znear, float zfar,
                             float eyex, float eyey, float eyez, float centrex, float centrey,
                             float centrez, float upx, float upy, float upz,
                             float (&model_matrix)[16],
                             float (&view_matrix)[16],
                             float (&projection_matrix)[16])
{
    get_model_matrix(model_matrix);
    get_view_matrix(eyex, eyey, eyez, centrex, centrey, centrez, upx, upy, upz, view_matrix);
    get_projection_matrix(fovy, aspect, znear, zfar, projection_matrix);
}

void get_model_matrix(float (&in_a)[16])
{
    // Identity matrix
    in_a[0] = 1; in_a[4] = 0; in_a[8] =  0; in_a[12] = 0;
    in_a[1] = 0; in_a[5] = 1; in_a[9] =  0; in_a[13] = 0;
    in_a[2] = 0; in_a[6] = 0; in_a[10] = 1; in_a[14] = 0;
    in_a[3] = 0; in_a[7] = 0; in_a[11] = 0; in_a[15] = 1;
}

void get_view_matrix(float eyex, float eyey, float eyez, float centrex, float centrey, float centrez, float upx, float upy, float upz, float (&in_a)[16])
{
    vertex_3 f, up, s, u;

    f.x = centrex - eyex;
    f.y = centrey - eyey;
    f.z = centrez - eyez;
    f.normalize();

    up.x = upx;
    up.y = upy;
    up.z = upz;
    up.normalize();

    s = f.cross(up);
    s.normalize();

    u = s.cross(f);
    u.normalize();

    in_a[0] = s.x;  in_a[4] = s.y;  in_a[8] = s.z;   in_a[12] = 0;
    in_a[1] = u.x;  in_a[5] = u.y;  in_a[9] = u.z;   in_a[13] = 0;
    in_a[2] = -f.x; in_a[6] = -f.y; in_a[10] = -f.z; in_a[14] = 0;
    in_a[3] = 0;    in_a[7] = 0;    in_a[11] = 0;    in_a[15] = 1;

    float translate[16];
    translate[0] = 1; translate[4] = 0; translate[8] = 0;  translate[12] = -eyex;
    translate[1] = 0; translate[5] = 1; translate[9] = 0;  translate[13] = -eyey;
    translate[2] = 0; translate[6] = 0; translate[10] = 1; translate[14] = -eyez;
    translate[3] = 0; translate[7] = 0; translate[11] = 0; translate[15] = 1;

    float temp[16];
    multiply_4x4_matrices(in_a, translate, temp);

    for(size_t i = 0; i < 16; i++)
        in_a[i] = temp[i];
}

void get_projection_matrix(float fovy_degrees, float aspect, float znear, float zfar, float (&in_a)[16])
{
    const static float pi = 4.0f*atanf(1.0);

    // Convert fovy to radians, then divide by 2
    float f = 1.0f / tan(fovy_degrees/360.0f*pi);

    in_a[0] = f/aspect; in_a[4] = 0; in_a[8] = 0;                              in_a[12] = 0;
    in_a[1] = 0;        in_a[5] = f; in_a[9] = 0;                              in_a[13] = 0;
    in_a[2] = 0;        in_a[6] = 0; in_a[10] = (zfar + znear)/(znear - zfar); in_a[14] = (2.0f*zfar*znear)/(znear - zfar);
    in_a[3] = 0;        in_a[7] = 0; in_a[11] = -1;                            in_a[15] = 0;
}


text:
Tell if two polygons are colliding
I want to make a function like areColliding which takes two polygons as args.
I also want to cover cases like

and the dreaded

because I am trying to create a framework and I think that it should be as accurate as possible.
var polygon1 = [
  [1, 1],
  [2, 5],
  [5, 3],
];
var polygon2 = [
  [1, 1],
  [2, 5],
  [3, 5],
  [7, 4],
  [1, 3],
  [2, 1],
  [1, 0],
];
areColliding(polygon1, polygon2) //=> true
areColliding([[1, 4]], [[1, 2], [3, 4], [5, 6]]) //=> Error
areColliding({}, [[1, 2], [3, 4], [5, 6]]) //=> Error
areColliding([[1,1],[2,2],[3,0]], [[7,7],[5,7],[6,8]]) //=> false

So, presumably you did a search for standard algorithms for this and found options like Separating Axis Theorem, GJK, etc? What have you tried based on your research thus far?


text:
How can I mod a Minecraft slime to be about the size of a full block?
I want to make the slime's size roughly the size of a full block,
I have tried some values but I'm not sure if any of those I tried fit the idea I have.
What would you recommend for the size of the slime which roughly matches or matches a block's size?

You can't.
You can't make a "size" 1.8 slime. The closest you can get is a size 2 slime because Slime.setSize(int) only takes an integer because the Size NBT tag within a slime only takes an integer too.
See this.


text:
UI event issues with reaction game
I'm making my first real video game. You have to click either on the left or right side on time or else you lose (note: the code I'm about to post doesn't have the timing, don't worry about that, I haven't added it yet). My question is why when the player clicks a UI button that's on the left or right side based on where they're instructed to click, nothing... happens. This is the main script, and all of it is relevant because the whole game isn't done yet, and this small amount is just what I've created so far.
I have done my research. I have been looking up everything I can think of for the past day now.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Advertisements; // coming soon

public class Game: MonoBehaviour {

  public Button playBtn;

  public Button clickSideLBtn;
  public Button clickSideRBtn;

  public Text clickSideLTxt;
  public Text clickSideRTxt;

  public Image playIcon;
  public Image pauseIcon;

  private float correctSide = 0;

  private GameManager gameManager;

  private bool hasAnswered = true;

  private AudioSource audioData;

  private void setSideActive(float side, bool state) {
    if (state) {
      correctSide = side;
    } else {
      if (side == 0) {
        correctSide = 1;
      } else {
        correctSide = 0;
      }
    }

    if (side == 0) {
      clickSideLTxt.gameObject.SetActive(state);
      clickSideLBtn.gameObject.SetActive(state);
    } else {
      clickSideRTxt.gameObject.SetActive(state);
      clickSideRBtn.gameObject.SetActive(state);
    }
  }

  void Start() {
    audioData = GetComponent<AudioSource>();

    gameManager = GetComponent<GameManager>();

    pauseIcon.gameObject.SetActive(false);

    gameManager.gameIsStarted = false;

    setSideActive(0, false);
    setSideActive(1, false);

    StartCoroutine(HandleUpdate());
  }

  private IEnumerator HandleUpdate() {
    for (;;) {
      DoUpdate();

      yield return new WaitForSeconds(2.0f);
    }
  }

  void DoUpdate() {
    if (gameManager.gameIsStarted && hasAnswered) {
      hasAnswered = false;

      if (Random.value > 0.5f) {
        setSideActive(0, true);
        setSideActive(1, false);
        audioData.Play(0);
      } else {
        setSideActive(1, true);
        setSideActive(0, false);
        audioData.Play(0);
      }
    }
  }
  void OnEnable() {
    //Register Button Events
    playBtn.onClick.AddListener(() => playBtnCallback());
    clickSideRBtn.onClick.AddListener(() => clickSideR());
    clickSideLBtn.onClick.AddListener(() => clickSideL());

  }

  private void playBtnCallback() {
    if (gameManager.gameIsStarted) {
      gameManager.EndGame();
    } else if (!(gameManager.gameIsStarted)) {
      gameManager.gameIsStarted = true;
      playIcon.gameObject.SetActive(false);
      pauseIcon.gameObject.SetActive(true);
    }
  }

  private void clickSideR() {
    if (correctSide == 1) {
      hasAnswered = true;
      setSideActive(1, false);
      // yay, you did it right, don't do anything, other scripts keep the game alive until you tell it not to
    } else {
      gameManager.EndGame();
    }
  }

  private void clickSideL() {
    if (correctSide == 0) {
      hasAnswered = true;
      setSideActive(0, false);
      // yay, you did it right, don't do anything, other scripts keep the game alive until you tell it not to
    } else {
      gameManager.EndGame();
    }
  }
}

Did you try to add a breakpoint and step-by-step debug your code?

I will try that.


text:
Add 1 to a PlayerPref float if a day has passed in Unity 2D
I'm making a daily rewards system in my Unity 2D game. For each real-life day the user logs in (not necessarily consecutive) the player earns a Reward Point. Reward Points do two things:

Increase the rarity of what the player may obtain from Reward Chests.
Increase the frequency that a player may open a Reward Chest. The frequency starts at 24 hours, and for each Reward Point, it is decreased by 24 hours. (The frequency a player earns a Reward Point is not increased, just the frequency that the player can open a chest.)

I am asking how to check if a day has passed since the player last opened the game, and, if they have, add 1 to a PlayerPrefs float (this float contains the amount of Reward Points). I am familiar with Time, but I'm not sure how to accomplish my goal with it.
.

PlayerPrefs is not a good place for this data. It's very easy for players to edit, to set themselves to the maximum streak at all times. So I recommend using a server-side solution if you don't want players to exploit this.

Hmm... I don't actually have a server or anything. I'm just an indie developer; I do this with 6 other friends. Still, though, thank you for the information about PlayerPrefs.

However, this is just an offline game. I know the player could cheat, but would it matter if they did? It wouldn't affect anyone except themselves.

On startup of the game / scene load or main menu get the current time as timestamp. You store as well the timestamp of last awarded reward. Now all you need to do is subtract them and check if the difference is one day or bigger. As pointed out, easy to cheat if offline or locally. But this logic will work the same if you place the check later on the server and exchange playerpref for a small db

Note the concerns in the comments that data stored in PlayerPrefs is easy for players to modify, and checks based on local system time can easily be cheated by changing your system clock. If you don't mind this reward being cheated, that's fine - just be aware that it will happen.
If you want to make this harder to cheat, you can spin up a cheap server and database. Make a web request to the server to ask for the reward point value. The server will receive the request, and check this player's row in the database, updating it based on the server time, then send the result back. That puts the clock and storage outside the player's reach.
That said, if you're happy with a cheatable local version, you can do something a bit like this:
// Store the keys to read/write in PlayerPrefs as constants, so we don't make typos.
const string DAY_LAST_PLAYED_ID = "DayLastPlayed";
const string DAYS_PLAYED_ID = "DaysPlayed";

// Keep track of how many days we've played before today.
// Zero for the whole first day of play, one on the second, two on the third...
int _previousDaysPlayedCount;

// Helper method to decode a timestamp from a string we stored in PlayerPrefs.
bool TryReadDate(string text, out System.DateTime date) {
    return System.DateTime.TryParseExact(text, "O",
               System.Globalization.CultureInfo.InvariantCulture,
               System.Globalization.DateTimeStyles.RoundtripKind, out date);
}

// Helper method to encode a timestamp into PlayerPrefs,
// and save it to disc so it's not lost if we close unexpectedly.
void RecordPlayDay(System.DateTime date) {
    PlayerPrefs.SetString(DAY_LAST_PLAYED_ID,
                date.ToString("O", System.Globalization.CultureInfo.InvariantCulture));
    PlayerPrefs.Save();
}

// Call this function when your game starts up or regains focus,
// or at intervals during play to credit a day roll-over mid-session.
void UpdateDaysPlayed() {
    // Refresh our day played count from the stored value,
    // or use zero if this is our day and we haven't written it yet.
    _previousDaysPlayedCount = PlayerPrefs.GetInt(DAYS_PLAYED_ID, 0);

    var today = System.DateTime.Now.ToUniversalTime();

    // Get our saved timestamp from the last day we played, and try to parse it.
    var lastPlayString = PlayerPrefs.GetString(DAY_LAST_PLAYED_ID, "");
    System.DateTime lastPlayDate = default;

    if (string.IsNullOrWhiteSpace(lastPlayString)
        || !TryReadDate(lastPlayString, out lastPlayDate)) {
        // If we didn't have a valid date saved, then this is our first day.
        // Write that info as a starting point to compare to later.
        RecordPlayDay(today);
    } else {
        // If we do have a valid date saved from last time,
        // compare it to the current time. If the difference is at least
        // 24 hours, then we're playing on a new day.
        var difference = today - lastPlayDate;
        if (difference.TotalHours >= 24.0) {
            // It's a new day! Increment our count and save that information.
            _previousDaysPlayedCount++;
            PlayerPrefs.SetInt(DAYS_PLAYED_ID, _previousDaysPlayedCount);
            RecordPlayDay(today);
        }
    }
}

Note that we only update the saved timestamp when it's been a full 24 hours since our last timestamp. That way if you play frequent short sessions multiple times a day, you don't keep kicking the threshold forward without ever ticking it over.

I've been working on securing my game system right now, by the way. I used a tutorial by Brackey's on YouTube to help me change it so that now the data is saved in binary format in a file. Still not perfect, but I think it will be a bit more secure until I set up a webserver.

There's an error in your code. I already fixed the returnSystem. . . typo (I think it mean to be return System. . ., right?, but it also says "expected ;" and "expected }`". I obviously tried placing what it told me to into there, but it didn't really help. Do you know what's

That's not enough information for me to help you. I've adjusted some minor typos above — beyond that, listen to your compiler.


text:
One global game loop vs multiple local game loops
What are the advantages of using multiple game loops instead of one?
Assume Level1, Level2, Level3. These levels may bring totally different problems and needs and they may also be completely separate, perhaps like a classic Mario game. One level needs multiple frame counters yet the others need none. Would it make sense to structure a game like that, with many loops?
I've written an implementation of this, which was actually my first loop design for my game, and memory management looks like few necessary global with many local variables, at the cost of less automated code (meaning more writing).
Is this done at all and if so, is this common?

The cost of rewriting your loop is not worth any perceived benefits of having "more efficient" loops that leave out unneeded bits.
This is "premature optimization". I would not consider multiple loops unless

A profiler tells you the code in the loop is causing bottlenecks (very unlikey)
Your levels are so different from one another that shared code is minimal

Re: 2, even if the shared code is minimal, I'd still recommend using a single loop with swappable "guts" - like a Strategy pattern or Execute-Around pattern - so even that minimal glue lives in a single place. Duplicating that code for each level would be planting land mines for any future changes. Forget to update just one, or update it incorrectly, and you've introduced a subtle bug that won't show up in most tests.

The "rewriting your loop" point makes using one loop compelling. The problem is that I'd still have a giant memory problem because I'd have to use lots of generically named globals, passed through the preprocessor, and perhaps put variables to the heap, which makes this choice actually hard. The "unneeded bits" are not an issue as there really aren't any.

@senatorsteven "memory problem" do you think you'll hit the RAM limit anytime soon?

Is the profiler telling you that you have RAM issues?


text:
How to calculate the shadow bounding box with a directional light
I'm trying to implement a directional light in my C++ / OpenGL engine, but I struggle to calculate the shadow bounding box (i.e the shadow frustum).
The bounding box has to encompass the main frustum and be aligned with the light rays, resulting in an orhographic frustum.
The problem is that as the light have no position, I don't know how to create the light view matrix, which is necessary to calculate the aligned bounding box.
Here's my current attempt:

calculation of the main frustum 8 coordinates in world space
conversion of these 8 coordinates in light view space, using the lightView matrix
calculation of a bounding box around the main frustum, aligned with light rays since I'm in light view space
calculation of the bounding box center, in light view space
conversion of the bounding box center in world space (using the inverse of the lightView matrix)
calculation of the bounding box projection matrix with glm::ortho
calculation of the bounding box view matrix (the lightView matrix) with glm::lookAt. For this I need the bounding box center, which I calculated... using the lightView matrix.

This doesn't work, because I need the lightView matrix to calculate the bounding box center. But I need the bounding box center to calculate the lightView matrix.
I can't manage to get it right. What am I missing?
Here is the code:
void Shadows::updateFrustumBoundingBox()
{

  // Here we convert main camera frustum coordinates in light view space
  std::array<glm::vec3,8> points = {
    // Near plane points
    lightView * glm::vec4(cameraPtr->ntl, 1.0),
    lightView * glm::vec4(cameraPtr->ntr, 1.0),
    lightView * glm::vec4(cameraPtr->nbl, 1.0),
    lightView * glm::vec4(cameraPtr->nbr, 1.0),
    // Far plane points
    lightView * glm::vec4(cameraPtr->ftl, 1.0),
    lightView * glm::vec4(cameraPtr->ftr, 1.0),
    lightView * glm::vec4(cameraPtr->fbl, 1.0),
    lightView * glm::vec4(cameraPtr->fbr, 1.0)};

  // Here we find the shadow bounding box dimensions
  bool first = true;
  for (int i=0; i<7; ++i)
  {
    glm::vec3* point = &points[i];

    if (first)
    {
            minX = point->x;
            maxX = point->x;
            minY = point->y;
            maxY = point->y;
            minZ = point->z;
            maxZ = point->z;
      first = false;
    }

        if (point->x > maxX)
            maxX = point->x;
    else if (point->x < minX)
            minX = point->x;

        if (point->y > maxY)
            maxY = point->y;
    else if (point->y < minY)
            minY = point->y;

        if (point->z > maxZ)
            maxZ = point->z;
    else if (point->z < minZ)
            minZ = point->z;
  }

  frustumWidth = maxX - minX;
  frustumHeight = maxY - minY;
  frustumLength = maxZ - minZ;

  // Here we find the bounding box center, in light view space
  float x = (minX + maxX) / 2.0f;
  float y = (minY + maxY) / 2.0f;
  float z = (minZ + maxZ) / 2.0f;
  glm::vec4 frustumCenter = glm::vec4(x, y, z, 1.0f);

  // Here we convert the bounding box center in world space
  glm::mat4 invertedLight = glm::mat4(1.0f);
  invertedLight = glm::inverse(lightView);
  frustumCenter = invertedLight * frustumCenter;

  // Here we define the light projection matrix (shadow frustum dimensions)
  lightProjection = glm::ortho(
    -frustumWidth/2.0f, // left
    frustumWidth/2.0f, // right
    -frustumHeight/2.0f, // down
    frustumHeight/2.0f, // top
    0.01f, // near
    SHADOW_DISTANCE); // far

  // Here we define the light view matrix (shadow frustum position and orientation)
  lightDirection = glm::normalize(lightDirection);
  target = glm::vec3(frustumCenter) + lightDirection;

  lightView = glm::lookAt(
                  // Shadow box center
                  glm::vec3(frustumCenter),

                  // Light orientation
                  target,

                  // Up vector
                  glm::vec3( 0.0f, 1.0f,  0.0f));

  // Final matrix calculation
  lightSpaceMatrix = lightProjection * lightView;
}

The only part of the LightView matrix that the bounding box center should affect is its translation, which doesn't change anything about the light. So couldn't you use an arbitrary translation (say, the translation from the previous frame, or to the player, or to the center of the view frustum) for your first step, then use the result to calculate a revised matrix with a new translation for the later step?

Thank you a lot for your help DMGregory. It helped me to find the solution, which I posted below. Have a good day.

Well, probably not the best way but this works pretty well.
Before to process the shadow bounding box, calculate a lightView matrix based on the main frustum center, with the light view set to a position relative to this center.
  lightView = glm::lookAt(
            // Eye
            cameraPtr->adaptativeFrustumCenter + lightPosition,
            // Target
            cameraPtr->adaptativeFrustumCenter,
            // Up vector
            glm::vec3( 0.0f, 1.0f,  0.0f));

When the shadow bounding box is processed, we have access to its center in world space. So we can update the lightView matrix. This updated view matrix will be then used to render the depth map.
lightView = glm::lookAt(
            // Eye
            glm::vec3(shadowFrustumCenter) + lightPosition,
            // Target
            glm::vec3(shadowFrustumCenter),
            // Up vector
            glm::vec3( 0.0f, 1.0f,  0.0f));


text:
Create buttons in the editor
So I've seen people  do stuff like
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class [ScriptName] : Editor
{
   // A bunch of code that I can't understand.
}

but what exactly do they do to make buttons on their script?

This is usually done by overriding OnInspectorGUI and including a call to GUI.Button, or the newer method with UIElements by overriding CreateInspectorGUI and creating a Button element. If you can explain what specific code you need help with, we can target answers to help with the specific aspect you're confused about.

However, if you don't understand any of it, then you might be a bit early in your learning journey yet for this particular task, and you may want to consider following some beginner tutorials to get a solid grasp of the language and the conventions for how it's used in Unity before returning to this problem.

Unity provides an ability to override the OnInspectorGUI function which is called when drawing an inspector window for a specific script.
The way it works is you can just create a new class derived from Editor class and tell the unity to create our custom inspector windows for your specific script.
And then in your OnInspectorGUI you can ask unity to draw all sorts of controls including buttons, color dialogs, sliders, etc!
Now to make a simple button with the traditional "Hello World" text, follow this code:
using UnityEngine;
using UnityEditor;

public class MyScript : MonoBehaviour
{
    public bool doesntMatter;
}

[CustomEditor(typeof(MyScript))]
public class MyScriptEditor : Editor
{
    void OnInspectorGUI()
    {
        var myScript = target as MyScript;
        myScript.doesntMatter= EditorGUILayout.Toggle("Hello World"); //Returns true when user clicks
    }
}

Now if you've got a good grasp, here's something that you might actually need when creating custom inspector windows:
When the user toggles a checkmark, more variables wqill be shown to the user.
using UnityEngine;
using UnityEditor;

public class MyScript2 : MonoBehaviour
{
    public bool show = false;
    public int num1;
    public float num2;
    public bool anotherToggle = false;
    public GameObject go;
}

[CustomEditor(typeof(MyScript2))]
public class MyScript2Editor : Editor
{
    void OnInspectorGUI()
    {
        var myScript2 = target as MyScript2;

        myScript2.show = EditorGUILayout.Toggle("Show Hidden Values");
        myScript2.anotherToggle = EditorGUILayout.Toggle("Show Another Hidden Value");

        if(myScript2.show)
            myScript2.num1 = EditorGUILayout.IntField("Enter a number:", myScript2.num1);
            myScript2.num2 = EditorGUILayout.Slider("Choose float between 1 to 10:", myScript2.num2, 0, 10f);
            if(myScript2.anotherToggle)
                myScript2.go = EditorGUILayout.ObjectField("Very hidden gameObject:", go, typeof(GameObject));
    }
}

Hope this helped you create your first inspector windows :)

This is actually very simillar to a Brackeys video I watched about custom inspectors

cannot convert string to boolean for you first example, on this line myScript.doesntMatter= EditorGUILayout.Toggle("Hello World"); //Returns true when user clicks

A solution I often use is creating "pseudo-buttons" using bools and Unity's OnValidate() method
    void ExampleMethod()
    {
        Debug.Log("Hello World!");
    }

    public bool pseudoButton = false;
    void OnValidate()
    {
        if (pseudoButton)
        {
            ExampleMethod();

            pseudoButton = false;
        }
    }

It's a bit of a hacky, but its useful for quick debugging, and to not waste time with creating a new custom


text:
Move between two points at a constant speed in LWJGL
I've been making a game engine in lwjgl and I have been trying to get an ai to move from one point to another. I used a lerp method but the speed is dependent on the distance between the two points, where I need the speed to be constant
    public static Vector3f moveTo(Vector3f currentPos, Vector3f targetPos, float speed)
    {
        float x = lerp(currentPos.x, targetPos.x, speed);
        float y = lerp(currentPos.y, targetPos.y, speed);
        float z = lerp(currentPos.z, targetPos.z, speed);

        return new Vector3f(x, y, z);
    }

I was thinking of dividing by the distance, like this:

    public static Vector3f moveTo(Vector3f currentPos, Vector3f targetPos, float speed)
    {
        float dist = distance(currentPos, targetPos);
        float x = lerp(currentPos.x, targetPos.x, speed / dist);
        float y = lerp(currentPos.y, targetPos.y, speed / dist);
        float z = lerp(currentPos.z, targetPos.z, speed / dist);

        return new Vector3f(x, y, z);
    }

but the results are... weird, to say the least.

You're using an exponential ease-out lerp here, which is why you see the behaviour of slowing down on approach.

Your question is not about lwjgl or implementation. It's about physics and math in fact.
Velocity from definition is v = s/t.
You want v = const and you know distance s = distance(target, source), hence you have
t = s/v = distance(targer,source)/velocity -- answering "what's the total time it will take for object to move from source to target?".
What does a moveTo() function do?
If it's meant to determine the position on a segment [A,B], then it has to ask "at what point in time?" and be called getPosition - not moveTo, because it deosn't tell the object to move -- it answers where would it be at given time. This should then have a signature position(source, target, speed, t).
From source and target you derive distance, speed is your constant, and then you determine your timeTotal=s/v (how long it takes to travel from A to B). Doing t/timeTotal = t / (distance(target,source)/velocity) gives you a fraction in range [0,1] that you then use, to lerp from A to B:
position(A, B, speed, t) => lerp(A,B, t/(distance(A,B)/speed))

This method returns absolute position at given time t of the movement, assuming that the object has uniform motion. It's good in scenarios, when you have a "keyframe" for A, B and want to interpolate between them (like in blender for example).
On the other hand when you want to apply motion in one tick of your physics simulation and you know, that the velocity is constant, then simply ds = v*dt (delta movement is velocity times delta_time of the physics).
moveTo(currentPos, target, speed, dt) => currentPos + normalize(target-currentPos)*speed*dt

where normalize(target-currentPos)*speed is direction vector scaled by speed, thus velocity vector.
Both methods are useful in different scenarios - first is related to Tweening, second is related to physics simulation (but doesn't generalize well in current form).
If you want more accurate movement with varying acceleration (right now your acceleration is constant and 0, cuz speed is constant), then you should check out methods such as Euler integration, Runge-Kutta integration or (prefereably) Verlet integration (because it +-conserves energy). If you want to read about them, check them out in context of games and algorithms, otherwise you will get lost in the mathematical jargon of the Wikipedia


text:
Is it okay to describe what software was used to develop the game in the credits screen?
I'm making a racing game, I've made my own game engine from scratch, but not the tools for building the game assets such as textures, 3D models, etc.
And I was thinking, I have this credits scene at the end of the story, where it basically shows some concept arts used during the development, and some photos of people involved in the development, and so I thought to add a list of software tools that were used to make the game.
Is it okay to do this? Of course this is in good faith, but is there a possibility that someone could come after me because I used their trademark without permission?
I mean this would basically be "free advertising" but I don't know...
What do you the gamedev community think of this?

I don't think you should ask the gamedev community this, we are not lawyers. Instead you should probably either consult a real lawyer andor study any logo/brand guidelines provided by the software you want to credit.

I'm not a lawyer. This does not constitute legal advice.

You can mention them, yes. Nothing prevent you from doing this.
In fact, some license agreement require mention, and end credits is a good place to do so.

For trademark and logos, you need to find what guidelines the author has for using them. If there are no such guidelines, it is probably better you ask the authors about it.
In general is it OK to show the logos as long as it is a way the way its holders agree with. And you would want a legal disclaimer (something along the lines of making it clear that they didn't make your game, and you don't work for them, ask a lawyer about such disclaimers).

Screenshots of the software is a different thing. If the tool is open source (under a license approved by the open source initiative), then you would be in the clear to use screenshots.
Otherwise, I'd avoid doing it without permission of the authors to be safe.  Although - in my personal opinion - legal action is probably not very likely because you are not competing with them. But remember that screenshots could include icons and other GUI elements that could be under copyright. It is also possible to argue that an screenshot is derivative work.

About the "free advertisement" approach, end credits is not the most visible place. You may consider selling a space in a splash screen, for example for an sponsorship. But that is an entirely different thing.
The flip side is, of course, that as I said above, some license agreements require mention. Which is common with free tools and assets. Thus, you can think of this "free advertisement" as what they get in exchange. Review your licenses.

My understanding is that as a general rule, you want to make sure you're naming/showing third parties' logos only in ways that do not imply affiliation or endorsement. Imagine if someone put out a very low-quality game and slapped the Autodesk logo prominently somewhere. A consumer might misinterpret that to mean that this was produced in official partnership with Autodesk or that Autodesk in some way approved and endorsed this game, which could then give them a negative impression of that company's standards of quality. That's the type of scenario I know of where this may be unappreciated.

Contact the makers of the tools you are describing and ask them. You might get some free advertising in return from them!


text:
Unity C# XML How to load a saved position and a saved stage
I have a problem. I already figured out how to save the player stats (including the player position). But every time I load it back, the player ends up in the saved position but still within the open scene, not the saved scene. Nothing else got passed, no errors. Nothing happened except for the player ending up in the saved position, yet still within the open scene, not the saved scene. Here is the code:
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.SceneManagement;
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;

    public class ReadWrite : MonoBehaviour
    {
        public string path;
        public PauseScreen ps;
        public SaveData activeSave;
        public bool hasLoaded;
        public PlayerController ball;

        void Start()
        {
            hasLoaded = false;
            ps = FindObjectOfType<PauseScreen>();
            ball = FindObjectOfType<PlayerController>();
        }

        public void SaveGame()
        {
            string dataPath = Application.persistentDataPath + "/" + "Save.txt";
            activeSave.unitName = SceneManager.GetActiveScene().name;
            SpawnPointChoice.SetSpawnPoint(activeSave.unitName);
            activeSave.score = ScoreSystem.score;
            activeSave.lives = LivesSystem.lives;
            var serializer = new XmlSerializer(typeof(SaveData));
            var stream = new FileStream(dataPath, FileMode.Create);
            serializer.Serialize(stream, activeSave);
            stream.Close();
            Debug.Log("Your game has been saved.");
            ps.Resume();
        }

        public void LoadGame()
        {
            string dataPath = Application.persistentDataPath + "/" + "Save.txt";
            if (!File.Exists(dataPath))
            {
                Debug.LogError("FILE NOT FOUND");
            }
            var serializer = new XmlSerializer(typeof(SaveData));
            var stream = new FileStream(dataPath, FileMode.Open);
            activeSave = serializer.Deserialize(stream) as SaveData;
            stream.Close();
            ball.transform.position = activeSave.transformPosition;
            SceneManager.LoadScene(activeSave.unitName);
            ScoreSystem.score = activeSave.score;
            LivesSystem.lives = activeSave.lives;
            Debug.Log("Your game has been loaded");
            hasLoaded = true;
            ps.Resume();
        }
    }

    [Serializable]
    public class SaveData
    {
        public Vector2 transformPosition;
        public int score;
        public int lives;
        public Scene unit;
        public string unitName;
    }

The line where I have a comment saying "Load saved scene" is where I need assistance. Any would be appreciated.
Edit: Now, right after the game was successfully loaded, it reloaded the start of the game.
Sincerely,
Jay Burch

Comments are not for extended discussion; this conversation has been moved to chat.

SceneManager.LoadScene("") tries to load a scene with an empty name, which is not going to work. You likely intend to do SceneManager.LoadScene(activeSave.unit.name), which is the variable where you saved the name of the current scene to.

Yeah, didn't work. Came up with an error, which was what I was afraid of. Cannot load scene: Invalid scene name (empty string) and invalid build index -1

Sounds like your save file was lacking a saved scene name, or the scene name didn't correctly get deserialized into your activeSave variable. Try debug logging the value of activeSave.unit.name. You might also want to consider making activeSave.unit a plain string variable, and saving just the name into it.


text:
How to manage huge number of vegetation positions across the world
How to manage positions of huge number of vegetation (grass in particular) in games?
Do the positions have to be memorized or do they have to be generated on the fly? If so, can the grass always have the same positions?
I see that noise can be used to generate positions but I'm not sure how to manage them afterwards.
Also, if you have resources on this subject, I would be glad to know them.

"Do the positions have to be memorized or do they have to be generated on the fly? If so, can the grass always have the same positions?" Only you can answer those questions. What are the requirements of your game regarding this?

We talked about this in [chat] just recently - see the start of the thread here. It includes links to a couple of GDC talks about distributing vegetation in Horizon Zero Dawn and working with noise functions.

Thank you both, I'm seeing the conferences right now.
My requirement is a top down game, with huge areas (say 100x100km for the example). I realize that even in memory I wouldn't have the space to store all that grass.


text:
In what circumstance might I need to output pixels in non-32-bit format?
Among practically existing devices people play games with - PC, mobile, PlayStation, XBox, Nintendo etc. - is there any possibility that a pixel on the screen is not 32-bit, and do I have to consider this for portability?

Probably the most notable area where more exotic pixel colour formats might come up is when using a high dynamic range (HDR) display, with a platform that supports it.
PC, Xbox One S/X / Series S/X, and PS4 / PS5 all support HDR output.
For example, the HDR10 spec uses 10 bits per colour channel, instead of the usual 8 used for SDR output.
In some situations you might output your frame in ARGBHalf format (16 bits per colour channel, 64 bits per pixel). This is often the default HDR output format in Unity, for example.


text:
How to not call the same Dear ImGui function several times per frame
I'm using this Dear ImGui code in a function called several times per frame, resulting in duplications of the called UI element.
ImGui::Begin("Hello World");
ImGui::SliderFloat("test", &foo, 0.0f, 100.0f);
ImGui::End();

Result:

How to correct this behaviour?
Can Dear ImGui be set to avoid this, or do I have to take care of this myself?

"do I have to take care of this myself?" Yep. We're not yet ready for having programs design themselves from "what we want them to do". Did you try to put this in an if( not flag ) { /* draw your thing */ flag = true; } and reset the flag every frame?

Why is this function called several times a frame? A function which is supposed to render should be called exactly once per frame.

Thanks for your answers. I asked that because ImGUI knows when there is a new frame (ImGui_ImplOpenGL3_NewFrame), so it could maybe have deal with it.
@Vaillancourt: yes this is what I thought :)

@tkausl: I'm new to ImGUI but the render functions I'm aware of (ImGui::Render and ImGui::GetDrawData) are in my main loop, called 1 time / frame. But I could be wrong?

I'm talking about I'm using this Dear ImGui code in a function called several times per frame. Why is this function called several times per frame?

@tkausl: to make a debug tool in a function called several times per frame. I put the ImGUI code I showed in this function to directly access its variables but maybe it's bad design?

It looks to me like we don't have enough context to help you call this function only once per frame. You'll need to expand your code example so we can see where the multiple calls arise.

It's kind of weird because I thought imgui would not create multiple widgets with the same label, "test". Also the system will not be bothered by anything in NewFrame because you are calling the window function every frame after NewFrame anyway

Originally I wanted to put Imgui code in situ, where I needed it.
Then, to resolve these duplicate problems I first used a "new frame" flag, but I found this solution a bit cumbersome to apply everywhere in the engine.
Finally I have found simpler to put all Imgui code into one class, with methods to display this or that Imgui window. This class is called one time in the main loop, and its methods use pointers to fetch the variables they need into the engine.
Thank you all!


text:
How do I change from virtual camera (e.g dolly track) to main camera?
I want to show a cinematic view of my scene and then be able to play it with the camera attached to my player.
I have set up a dolly track and virtual camera and all works fine but I can't then play as my main character.
How can I do this?

Searching for "cinemachine switch camera" turns up lots of results. What have you tried based on your research thus far? How do the results differ from what you want?

@DMGregory i ave 1 main cam and i virtual cam they all say with 2 virtual cams

You setup up two virtual Cams. One for your Cinematic View and one for your Playercharacter. The thing about the Cinemachine is, that the "real" camera switches to the position and paramteres of the virtual cameras. You can do the switching via the timeline, which isn't so flexibel
https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineTimeline.html
or
which seems for you more suitable via script and a "playbale director".
Just create an empty with a box collider, playable director and following script
public class CinematicsTrigger : MonoBehaviour
    {
        bool alreadyTriggerd = false;

        private void OnTriggerEnter(Collider other)
        {
            if (!alreadyTriggerd && other.gameObject.tag == "Player")
            {
                alreadyTriggerd = true;
                GetComponent<PlayableDirector>().Play();
            }

        }
    }

In the playbale director you need to reference a "playbale" "Timeline Asset".
A Timeline assets contains the virtualcameras for your cinematic. You can create a Timeline via rmb>create>Timeline
https://docs.unity3d.com/2017.1/Documentation/Manual/class-PlayableDirector.html


text:
GL error GL_INVALID_OPERATION: mismatched type setting uniform of location "4" in program "1"
I  get this error while trying  to add lighting
Message: Error has been generated. GL error GL_INVALID_OPERATION in Uniform1i: (ID: 2882512024) GL error GL_INVALID_OPERATION: mismatched type setting uniform of location "4" in program 1, "" using shaders, 2, "", 3, ""
type: ERROR --- id: 1282 --- severity: HIGH

this is my fragmentshader
out vec4 color;

in VS_OUT
{
    vec2 tc;
    vec3 normals;
}

fs_in;

layout(binding=0)uniform sampler2D tex;

uniform vec3 lightColor;

void main(void)
{
color= texture(tex, fs_in.tc)* vec4(lightColor, 1.0);

}

I have this in my render
GLint lightColor_location = glGetUniformLocation(program, "lightColor");
    glUniform1i(lightColor_location, 0);
    glUniform3f(lightColor_location, lightColor.r, lightColor.g, lightColor.b);

and this declared
glm::vec3 lightColor = glm::vec3(1.0f, 1.0f, 1.0f);
```

"mismatched type" seems like a fairly clear error message. What have you tried to do to solve the error?

glUniform1i(lightColor_location, 0);

This says "set lightColor to the single number value zero".
But lightColor isn't a single number - it's three numbers! You can't set a variable that wants three numbers by giving it only one.
The line immediately after that looks more correct:
glUniform3f(lightColor_location, lightColor.r, lightColor.g, lightColor.b);

Here we're trying to set a 3-component variable by giving it 3 numbers, so we've matched the input to the intended output.

The glUniform1i call possibly intends to set "tex" to 0, which is not actually necessary as it's already declared with binding 0.


text:
Changing Ambient Light settings in Environment window does not affect scene after baking LightMap
My settings:
Unity version - Unity 2021.1.12f1
Lightmap Lighting Mode - Bake indirect
Render Path - URP
I want to change Ambient Light in Environment window while I have baked LightMap. Is it possible?

Did you re-bake the lighting after you changed the ambient lighting setting?

@DMGregory I want change Ambient Light on Running without re-baking LightMap. Is it Possible?

...Just what is it that you think "baking" indirect lighting means?

@DMGregory Baking with "Bake Indirect" not bake shadows from Light Source, only from Ambient Light. I was hoping that the color of the shadows from the directional light in this case can be changed without re baking. Because in this case we have dynamic shadows that updating over time. Why we can't change the color of this dunamic shadows?

I find the way to change color of shadow by using post processing. Is this the only way to do this?

Hint: the colour you see in the shadows is from the light that is not the direct light - ie. it's the baked indirect and ambient light showing through in places that the direct light doesn't reach. If you've found a solution to your problem, post it as an answer below.

Coloring shadows is possible when using post-processing effects. I did not find any other options.

Your answer should walk through how to use post-processing effects to achieve this shadow colouring outcome. Aim to make the kind of thorough guide that you wish you'd found when first searching for help, and you can be that help for the next person who searches about this.


text:
LWJGL2 Camera Movement Stutter
I'm having quite some trouble with camera stutter in my LWJGL2 game. The stutter only occurs when moving the camera. When it stands still, the scene is rendered smoothly. I could verify that by animating the trees in the wind, and they don't stutter.
Also, I can confirm that the stutter was not introduced by the screen recording software, however I suspect that the recording made the stutter even worse.
My game uses delta-time multiplied with the velocities that are changed using the keyboard or directly by code.
Things I've already tried without success:

Turn VSync on
Remove all unrelated code
Try with 30fps cap and 60fps cap

It's also not related to my graphics drivers since a different LWJGL2 project based on the same engine runs smoothly.
I'm also running some background threads to handle networking and am reusing Vec3 and Mat4 instances when calculating projection and translation matrices.
Any ideas on what could cause the stutter?

Nevermind, after searching for hours I found the error. I was periodically calling a cpu-intense method that refreshed the minimap. After moving the execution of this method into an own thread, the stutter disappeared. It's also worth mentioning that the stutter was appeared periodically so it makes perfect sense now why this happened.


text:
Textmeshpro background color
Trying to get the  tag in text mesh pro to draw the mark color behind the actual text. According to this thread it's possible using a workaround where you use the  tag in combination with  to force the font geo to render in front.
Doesn't work for me though. This is the value of my text field: <mark=#FF80aaaa><font="LiberationSans SDF">test
I've trie various combinations but it always draws the mark in front of the text.


text:
SFML: Object's shape not rendered on the window
I want to be able to render sf::CircleShape (representing pointwise charges) when pressing mouse buttons on the window. The problem is easy enough, however the shapes that I want to draw are attributes of a class Charge. The Scene class implements window management and event polling/ rendering methods and it has an attribute std::vector<Charge> distribution.
The idea is to update the distribution variable everytime the event sf::Mouse::isButtonPressed is recorded and then draw the charges' shapes within such vector. For some reason I cannot make it work and I think it's due to the object being created and destroyed within the event loop.
I have a main that looks like this
#include "Scene.h"

int main(){

  Scene scene;

  while(scene.running())
  {
    scene.update();
    scene.render();
  }
  return 0;
}

with the header Scene.h declaring the class methods for window management and event polling
#include "Charge.h"

class Scene
{
    private:
        sf::RenderWindow* window;
        sf::Event event;
        std::vector<Charge> distribution;

public:
        Scene();
        virtual ~Scene();

        bool running();
        void polling();
        void render();
        void update();
};

The definitions of the methods instantiated in the game loop are
void Scene::update(){this -> polling();}

void Scene::polling()
{
    while(this -> window -> pollEvent(this -> event))
    {
        switch(this -> event.type)
        {
            case sf::Event::Closed: this -> window -> close();
                break;

            case sf::Event::MouseButtonPressed:
                this -> distribution.push_back(Charge(*this -> window, sf::Mouse::getPosition(*this -> window));
                std::cout << "Distribution size = " << distribution.size() << "\n";
                break;
        }
    }
}

void Scene::render()
{
    this -> window -> clear(sf::Color::Black);

    for(auto charge: this -> distribution)
    {
        charge.render(*this -> window);
    }

    this -> window -> display();
}

The window object is instatiated in the cosntrutor of Scene. Now Charge.h declares the class
class Charge
{
    private:
        sf::CircleShape shape;

    public:
        Charge(const sf::RenderWindow& window, sf::Vector2i position);
        virtual ~Charge();

        void render(sf::RenderTarget& target);
};

and the definition of its methods is the following
Charge::Charge(const sf::RenderWindow& window, sf::Vector2i position)
{
    std::cout << "Charge's object created!" << std::endl;
    this -> shape.setOrigin(sf::Vector2f(static_cast<float>(position.x), static_cast<float>(position.y)));
    this -> shape.setFillColor(sf::Color(255,50,50));
    this -> shape.setRadius(25.f);
}

Charge::~Charge(){std::cout << "Charge's object destroyed!" << std::endl;}

void Charge::render(sf::RenderTarget& target)
{
    target.draw(this -> shape);
}

I added printing on terminal in the constructor and destructor. The execution of the program does not render any of the objects' shapes when mouse buttons are pressed. The terminal however reports
Charge's object created! # <-- Here I pressed the mouse's button
Charge's object destroyed!
Distribution size = 1
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed! # <-- And it goes on and on as long as the window is not closed.

I tried to approach the problem in various ways but none have worked so far. Any idea?

You might want to make your Charge noncopyable (check boost's implementation), and add the default move ctor/move copy function...

I’m voting to close this question because it is a cross-post from stack overflow.

This block of code will be copying each object of type Charge for every iteration and assigning to the variable called charge.
  for(auto charge: this -> distribution)
  {
      charge.render(*this -> window);
  }

You need to change auto to auto& because you want to use a reference to the object itself not a copy of it. In most cases, this is the right approach in range-based for loops.
  for(auto& charge: this -> distribution)
  {
      charge.render(*this -> window);
  }

The first "Charge's object destroyed!" message is coming from the push_back method from the vector. Use emplace_back instead. It constructs the object inside the vector without doing any copying. It 'moves' the data to be exact.
this->distribution.emplace_back(*this -> window, sf::Mouse::getPosition(*this -> window));

There should not be any problems with the rendering in general. I don't see any issues with that. If you can show the problem in a gif, that would be better.

This solves the issue they report about having the object destroyed every frame, but does it solve the issue about the object not being rendered?

@Vaillancourt I am not sure if there is a problem with the rendering in general. I use this technique in rendering big chunks of primitives, and it works well enough. Not sure how this causes a problem though.


text:
Finding connected values of the same type within a 2D array
I am currently working on a puzzle game where blocks drop and you match nearby colors
Blocks are stored within a int 2D array that stores with a value between 1-3 once placed, and it should find connected blocks of the same value afterwards.
I believe this should be done by creating a function that when called, recursively finds same values next to the block, and add those within a list of 2D locations, then remove the values at those positions once all have been found.
How would this be done?
//this coroutine checks for all nearby blocks of same color//
public IEnumerator Flood(int x, int y, int OldCol, int NewCol) {
    WaitForSecondsRealtime wait = new WaitForSecondsRealtime(0.016f); //small delay//
    if(x >= 0 && x < BloackBoardWidth && y >= 0 && y < BlockBoardHeight) {//is the check in range?//
        yield return wait;
        if(GridCol[x,y] == OldCol) {//is the grid color same same as the old color?//
            //removes the color//
            GridCol[x,y] = 0;
            StartCoroutine(Flood(x + 1, y, OldCol, NewCol));
            StartCoroutine(Flood(x - 1, y, OldCol, NewCol));
            StartCoroutine(Flood(x, y + 1, OldCol, NewCol));
            StartCoroutine(Flood(x, y - 1, OldCol, NewCol));
        }
    }
}

It works roughly as you describe, have you tried to implement it? If you encounter an error, share your code and the wrong behaviour.

Currently have it working through a flood fill coroutine based method, it however ignores the minimum count needed
Edit: Function was too long, here's a pastebin https://pastebin.com/bpDciFqP

This sounds like a standard flood fill or connected component search, which you can implement with a basic depth-first or breadth-first search algorithm. Where have you run into trouble applying a standard approach like this to your case? Be sure to edit your question to show code and describe the problems with it – don't relegate important info like that to the comments.