text:
C++ OpenGL texture coords VBO indexes changes between models
I just load 3 models using assimp into my Engine and have some problems with textures. Through some research, I realized that texture coordinates VBOs indexes changes between models, according to this scheme:
At and of loading VBOs indexes of models is: 3 - first model, 6 - second model, 9 - third model, but the result:

I tried to do this:
    GLint texCoordAttributeLocation = glGetAttribLocation(Scene_Objects[i].Shader_Index, "texCoord");
    glEnableVertexAttribArray(texCoordAttributeLocation);
    if (i == 0) {
        glBindBuffer(GL_ARRAY_BUFFER, 9);
    }
    if (i == 1) {
        glBindBuffer(GL_ARRAY_BUFFER, 3);
    }
    if (i == 2) {
        glBindBuffer(GL_ARRAY_BUFFER, 6);
    }
    glVertexAttribPointer(texCoordAttributeLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);

And all textures showings right, why indexes changed to 9 - first model, 3 - second model, 6 - third model

I load 4 models and found regularity of indexes changes, the index of first loaded and last loaded model are swapped


text:
How to do Tileable Perlin Noise in C++?
I'm currently making a game that is going to involve terrain generation. I've already tried terrain generation using FastNoise2, and it "worked" and honestly would be faster than the "Roll your own" I'm going to try, but it'd be fun to roll my own anyway.
I managed to get normal 2D perlin noise working like so:
float Noise2D (int x, int y, int seed) {
  Random::gen.seed(x + y * 57 + seed); // <-- Random::gen is an instance of std::mt19937
  auto n = fmod(Random::RandomFloat(), 1); // <-- RandomFloat is a random range function; with no parameters it just makes the range 0-[whatever the default max float value in <random> is]
  Random::gen.seed(seed);
  return n;
}

float PerlinNoise2D(float x, float y, int seed) {
  auto floor_x = floor(x), floor_y = floor(y);
  auto s = Noise2D(floor_x, floor_y, seed);
  auto t = Noise2D(floor_x + 1, floor_y, seed);
  auto u = Noise2D(floor_x, floor_y + 1, seed);
  auto v = Noise2D(floor_x +  1, floor_y + 1, seed);

  auto frac_x = x- floor_x;
  auto frac_y = y - floor_y;
  auto value = s * (1 - frac_x) + t * frac_x;
  value += (u - s) * frac_y * (1 - frac_x);
  value += (v - t) * frac_x * frac_y;
  return  value;
}

And to test it:
void TestPerlinNoise() {
  int seed = Random::RandomFloat(0, 1000000);
  const int SIZE = 96;
  SDL_Surface* surface = SDL_CreateRGBSurface(0, SIZE, SIZE, 32, 0, 0, 0, 0);
  //float test[SIZE][SIZE];
  auto scale = (10.0f / float(SIZE));
  for (int y = 0; y < SIZE; y++) {
    for (int x = 0; x < SIZE; x++) {
      //test[y][x] = PerlinNoise2D(x, y, seed);
      auto noise = PerlinNoise2D(x * scale, y * scale, seed);
      Uint32 color = RGBA((uint8_t)(noise * 255), (uint8_t)(noise * 255), (uint8_t)(noise * 255), 255);
      SDLSetPixel(surface, x, y, color);
    }
  }
  IMG_SavePNG(surface, "test.png");
  SDL_FreeSurface(surface);
}

Which makes this image:
But how do I make the output of this function tileable?

Do you want to tile Perlin noise or value noise? As explained in this answer, your implementation generates value noise rather than Perlin noise. We already have a question & some answers on making tileable Perlin noise. Your solution isn't wrong, rather you're asking about one thing & implementing a different thing (that can give similar output) & without context, we don't know how to proceed.

source: Stack Exchange

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

sort: votes


text:
Is there any exsiting facial expression model libary?
I'm making a project and it needs 10 different facial expression.
After some reasearch,it seems that the only way is to use the facial rig.
But the rig will not fit different 3D model.
So I just wondering that if there anything like mixamo but for faical expression.

"What library should I use for..." questions are generally not on-topic for this site, but "How can I solve this problem..." questions are on topic, and answers can suggest libraries if they're helpful to solving the problem. Can you edit your question to focus more on the problem you need to solve, rather than your search for a library to solve it?

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


text:
2D Tilemap Collision resolution in C#/MonoGame
A bit of context about my game:
I'm nearly 2 years deep into development of my game called Cosmorists. It's programmed in C# using the .NET 7.0.11 framework, and MonoGame 3.8.1 game framework and it's a top-down tile-based game with regularly repeating square tiles. One problem has been weighing me down throughout the course of my development journey, and that's collision resolution.
Some context for implementation:
The game uses a tilemap, and it stretches to the 32-bit signed integer limits in both directions. They're stored as 16x16 chunks, and tile positions are represented as complex integers with real and imaginary values. Each tile is stored as a 16-bit unsigned integer representing the tile's index called "decor tiles". 0 is an empty tile.
Since it uses a tilemap, I know that this problem will be much easier for my case, as each tile is a 1x1 square, and the player's position is stored as a complex 64-bit floating point tile position.
What I know about this problem:
I know that this problem involves rays casting outwards, where the ray starts at the player's previous tile position, and ends at the current tile position. If the ray's endpoint is inside of a solid tile, the player's position will have to be set somewhere in between the start and endpoints of the ray, and one of the dimensions of the speed vector will be set to zero. This is where most of the struggles lie, or I may be wrong somewhere in there without knowing.
The C# code:
Here's the code that I have that handles collision resolutions:
void HandleCollisions() {

    if (!vehicleTarget.IsNull) {
        return;
    }

    ComplexDouble previousPreciseTilePosition = preciseTile;
    MoveX(frameLengthSeconds);
    MoveY(frameLengthSeconds);
    ComplexDouble currentPreciseTilePosition = preciseTile;

    if (GameDebug.NoPlayerCollision || (GameDebug.FastMovement && MaxTileMovementSpeed != defaultMaxTileMovementSpeed)) return;

    //Leave the method if the previous and current positions are equal, meaning that the player hasn't moved.
    if (previousPreciseTilePosition == currentPreciseTilePosition) return;

    //These two shift the coordinates to the correct positions depending on the sign of the tile positions.
    int xShift = currentPreciseTilePosition.A < 0 ? 0 : 1;
    int yShift = currentPreciseTilePosition.B < 0 ? 0 : 1;

    ushort GetDecor(ComplexInt tileOffset) {
        try {
            return MainWorld.GetDecorTile((ComplexInt)(preciseTile + (xShift - 1, yShift - 1)) + tileOffset, worldLayer);
        } catch (KeyNotFoundException) {
            return 0;
        }
    }

    //Take the mod one of the number, if it's negative, add one, so that the modulus doesn't go negative and is consistent with the positive modulus.
    double ModOne(double num) {
        double result = num - (int)num;
        if (result < 0) {
            result++;
        }
        return result;
    }
    //Rounds down the double to an integer similar to Math.Floor, this is so that the negative values are consistent with positive values.
    int RoundDown(double num) {
        int result = (int)num;
        if (num < 0 && result != num) {
            result--;
        }
        return result;
    }

    ushort topLeftTile = GetDecor((0, 0));
    ushort topRightTile = GetDecor((1, 0));
    ushort bottomLeftTile = GetDecor((0, 1));
    ushort bottomRightTile = GetDecor((1, 1));

    ComplexInt movementNormal = (Math.Sign(unnormalizedMovementSpeed.A), Math.Sign((float)unnormalizedMovementSpeed.B));

    bool IsSolidTileID(ushort tileID) => tileID != 0
    && (TileDecorProperties.ClassificationOf(World.IDToDecor[tileID]) == TileDecorProperties.Classification.Solid ||
        TileDecorProperties.ClassificationOf(World.IDToDecor[tileID]) == TileDecorProperties.Classification.Tree);

    if (movementNormal.A == -1 && (IsSolidTileID(topLeftTile) || IsSolidTileID(bottomLeftTile))) {
        if (ModOne(currentPreciseTilePosition.A) > 0.5) {
            preciseTile.A = RoundDown(currentPreciseTilePosition.A) + 1;
            unnormalizedMovementSpeed.A = 0;
        }
    }
    if (movementNormal.A == 1 && (IsSolidTileID(topRightTile) || IsSolidTileID(bottomRightTile))) {
        if (ModOne(currentPreciseTilePosition.A) <= 0.5) {
            preciseTile.A = RoundDown(currentPreciseTilePosition.A);
            unnormalizedMovementSpeed.A = 0;
        }
    }
    if (movementNormal.B == -CMath.I && (IsSolidTileID(topLeftTile) || IsSolidTileID(topRightTile))) {
        if (ModOne((double)currentPreciseTilePosition.B) > 0.5) {
            preciseTile.B = RoundDown((double)currentPreciseTilePosition.B) + 1;
            unnormalizedMovementSpeed.B = 0;
        }
    }
    if (movementNormal.B == CMath.I && (IsSolidTileID(bottomLeftTile) || IsSolidTileID(bottomRightTile))) {
        if (ModOne((double)currentPreciseTilePosition.B) <= 0.5) {
            preciseTile.B = RoundDown((double)currentPreciseTilePosition.B);
            unnormalizedMovementSpeed.B = 0;
        }
    }
}

Some context in the code above
The variable preciseTile is the player's current tile position, and it's a complex value with real and imaginary 64-bit float values.
frameLengthSeconds is a 32-bit float value representing how much time has passed between the previous and current frame in seconds.
vehicleTarget at the start doesn't relate to the problem, as it's responsible for knowing if the player is in a spaceship or not, and is merely an optimization.
GameDebug.NoPlayerCollision ||... This is a boolean that simply turns collision on or off when I debug the game, also doesn't relate to the problem.
Complex number context
The x position correlates to A, and the y position correlates to B, and the complex numbers can either be ComplexInt, ComplexFloat, or ComplexDouble. Here's example code demonstrating my implementation of them.
ComplexInt num = (10, 4);
num += 1;
//num: 11 + 4i
num += CMath.I;
//num: 11 + 5i
num += (2, -3);
//num: 13 + 2i
Console.WriteLine(num.A);
//num: 13
Console.WriteLine(num.B);
//num: 2i
Console.WriteLine(num.B * num.B);
//num: -4

Here are the methods that handle player movement.
private void MoveX(float frameLengthSeconds) {
    ComplexInt leftTile = (ComplexInt)preciseTile;
    ComplexInt rightTile = leftTile + 1;
    ushort leftDecorIndex;
    ushort rightDecorIndex;
    try {
        leftDecorIndex = Game1.MainWorld.GetDecorTile(leftTile, worldLayer);
        rightDecorIndex = Game1.MainWorld.GetDecorTile(rightTile, worldLayer);
    } catch (KeyNotFoundException) {
        leftDecorIndex = 0;
        rightDecorIndex = 0;
    }
    //Slows down the player if walking on a tile like water/oil, or speeds up if walking on a floor
    if (leftDecorIndex * rightDecorIndex != 0) {
        double xLeft = preciseTile.A - (int)preciseTile.A;
        if (xLeft < 0) {
            xLeft++;
        }
        double xRight = 1 - xLeft;
        xLeft = 1 - xLeft;
        xRight = 1 - xRight;
        TileDecor leftDecor = TileDecorProperties.ToDecor(leftDecorIndex);
        TileDecor rightDecor = TileDecorProperties.ToDecor(rightDecorIndex);
        double movementMultiplier = TileDecorProperties.SpeedMultiplierOf(leftDecor) * xLeft;
        movementMultiplier += TileDecorProperties.SpeedMultiplierOf(rightDecor) * xRight;
        preciseTile += movementSpeed.A * frameLengthSeconds * movementMultiplier;
    } else {
        preciseTile += movementSpeed.A * frameLengthSeconds;
    }
}
private void MoveY(float frameLengthSeconds) {
    ComplexInt upperTile = (ComplexInt)preciseTile;
    ComplexInt lowerTile = upperTile + CMath.I;
    ushort upDecorIndex;
    ushort downDecorIndex;
    try {
        upDecorIndex = Game1.MainWorld.GetDecorTile(upperTile, worldLayer);
        downDecorIndex = Game1.MainWorld.GetDecorTile(lowerTile, worldLayer);
    } catch (KeyNotFoundException) {
        upDecorIndex = 0;
        downDecorIndex = 0;
    }
    //Slows down the player if walking on a tile like water/oil, or speeds up if walking on a floor
    if (upDecorIndex * downDecorIndex != 0) {
        double xUp = (double)preciseTile.B - (int)preciseTile.B;
        if (xUp < 0) {
            xUp++;
        }
        double xDown = 1 - xUp;
        TileDecor upDecor = TileDecorProperties.ToDecor(upDecorIndex);
        TileDecor downDecor = TileDecorProperties.ToDecor(downDecorIndex);
        double movementMultiplier = TileDecorProperties.SpeedMultiplierOf(upDecor) * xUp;
        movementMultiplier += TileDecorProperties.SpeedMultiplierOf(downDecor) * xDown;
        preciseTile += movementSpeed.B * frameLengthSeconds * movementMultiplier;
    } else {
        preciseTile += movementSpeed.B * frameLengthSeconds;
    }
}

The current implementation of the collision resolution only sort of works. It does succeed in keeping the player out of solid tiles most of the time, but it still has bugs.
The bugs I've found so far:

The player will often clip to the corners of tiles when close to them.
If the framerate is low, the player can penetrate through solid tiles.
If the player moves very fast, they'll also penetrate through solid tiles.

My current implementation in action

In the gif above, the player will often teleport over small distances to the nearest tile to resolve to, and the player won't slide against a wall and they'll just clip against them when I try to move diagonally.
What I'm looking for:
Since I tried to make this problem easier for me by utilizing the fact that it's a square tilemap, I'll go with single point to tilemap collision resolutions instead to keep things simple.
Here's the approach that's the most promising for me, but I also had a hard time trying to implement. I have a ray in a square grid, where the size of each square is 1 and I want to get all the points that are intersecting this grid, and for the resulting list of points to be in order from the start to the end of the ray.
I'm looking for these blue points in the example images below ordered from the first number to the last one just before the arrow:

After getting these blue points and determining if the player has collided with a solid tile, I also somehow have to figure out which side the point it's on to know whether to set either the x or y velocity vector to 0 to enable the player to slide against a wall, as well as enabling travel through 1 tile wide gaps.
I also want this solution to get rid of the bug where the player will clip to the edges of the tile, and go through solid tiles at low frame rates or high speeds, even if it means that this solution will allow the sprite to partially overlap walls.
The question that I have, is how do I obtain these blue points in order from the start to the end of the ray as 64-bit float values, and figure out which side of the tile the point is colliding with in order to allow wall sliding and 1 tile wide gaps?

You may also be interested in Intersection of thick line with a grid (and the paper linked in the question, which covers the non-thick case of an infinitely small point swept across a grid).


text:
Anim notifies not working in unreal engine
. I think I have setup things needed to fireoff a custom AnimNotify, but, for some reason, custom notifies don't fire off. The premade notifies for playing sounds etc, fire off okay. But, this notify is something I made using Add Notify > New Notify . This event seems to be available in the character's blueprint which should mean the setup wasn't improper. Yet, the message doesn't get displayed in the screen. Am I missing to do something?


text:
Does unity transform world to local considering rotation
I want to implement oriented collision in unity as a test, and for convenience I just wanted to know if local space is also based on rotation. I wanted to check at least two objects against each other while also being accurate to their rotation. Is it true?

This sounds like a question you can answer by testing it. Have you seen any evidence that suggests rotation is NOT considered in these transformations?


text:
How to keep music playing continuously when switching scenes?
I added music to my game, but it restarts when transitioning between scenes. I want it to play continuously without interruption. What should I do?

I've linked this post to two earlier Q&A threads about playing music continuously across scene transitions. Remember to search for your keywords before posting, to help find answers faster. If you need help applying the existing answers in your game, you can edit your question to have it re-opened for answers to solve that specific issue.


text:
How to swap character model in PSX game?
I would like to know how I can change the 3D model of a PSX ROM running on an emulator.
For example, in Silent Hill 1, I would love to play as other characters by simply replacing the 3D models.
How can I do this?


text:
How to draw new tile on existing tilemap
I created a simple prototype/script which has to draw a predefined tile on an existing tilemap (and highlight the hovered tile).
But for some reason, even though it adds the tile to the correct place, it does not render it in game mode. The tile is only visible in edit mode. Why is that?
I am using Unity version 2022.3 with the Universal Render Pipeline (URP).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;

public class TilePlacer : MonoBehaviour
{
    public Tilemap tilemap;
    public TileBase tileToPlace;

    public Color highlightColor = new Color(1, 1, 1, 0.5f);
    private Vector3Int lastHighlightedCell = Vector3Int.one * int.MaxValue;

    private void Update()
    {
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3Int currentCell = tilemap.WorldToCell(worldPos);

        if (lastHighlightedCell != currentCell)
        {
            tilemap.SetColor(lastHighlightedCell, Color.white);
            tilemap.SetColor(currentCell, highlightColor);
            lastHighlightedCell = currentCell;
        }

        if (Input.GetMouseButtonDown(0) && tilemap.GetTile(currentCell) == null)
        {
            PlaceTileUnderMouse(currentCell);
        }
    }

    private void PlaceTileUnderMouse(Vector3Int currentCell)
    {
        tilemap.SetTile(currentCell, tileToPlace);
        tilemap.RefreshTile(currentCell);
    }
}


text:
Bone Indices from GLB Files
ChatGPT and I wrote a GlbImporter for a simple 3d engine written in Java. I can load any Glb model and extract and apply its diffuse textures. Extracting the bone animations is a different problem altogether. I'm pretty sure that the entire logic is written, except that I can't seem to read the bone indices for each vertex correctly. The following was written by ChatGPT, and it's only loading indices 1 or 1027. If anyone is willing to help, I could provide you with the entirety of the code.
private int[] extractBIArray(GlbData glbData, int meshIndex) {//Nine?
    GlbAccessor currentAccessor = glbData.boneIndicesAccessors.get(meshIndex);
    if (currentAccessor == null) {
        return null;
    }

    GlbBufferView bufferView = glbData.getBufferView(currentAccessor.getBufferView());
    int[] intArray = new int[currentAccessor.getCount() * 4]; // Four ints per component
    int byteOffset = bufferView.getByteOffset() + currentAccessor.getByteOffset();
    int bytesPerComponent = 4; // Each int is 4 bytes

    byte[] binaryData = glbData.getBinaryData();
    ByteBuffer buffer = ByteBuffer.wrap(binaryData);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    for (int i = 0; i < currentAccessor.getCount(); i++) {
        for (int j = 0; j < 4; j++) {
            int intValue = buffer.getInt(byteOffset + (i * 4 + j) * bytesPerComponent);
            intArray[i * 4 + j] = intValue;
        }
    }

    return intArray;
}


text:
unity wrong ragdoll behavior on slowmotion
I use simple logic to make a slow-motion effect. It works fine but it makes ragdoll animations feel like they have no weight and move easily.
This is the sample code:
    Time.timeScale += (1f / slowDownLength) * Time.unscaledDeltaTime;
    Time.timeScale = Mathf.Clamp(Time.timeScale, 0f, 1f);

I know it's based on fixedUpdate the physics engine used to run the physics simulation. If I want to do the time scaling manually with animation and speed, it can be a very hard process.


text:
How to add keyframe gaps on timeline animation window?
I'm using Unity timeline windows to create a building animation. I have a building model with many parts for example every floor has own parent and 200 child objects.

In this parent as you can see I added position animations with recording but I want gap between them.

For example like this:

But it's too hard to adjust it manually for so many objects. Is there any easy alternative?


text:
Creating a fake point light with empty object in the Unity shadergraph
I'm trying to create a fake point light from an Empty object with the shadergraph. This is a Blender prototype of the effect i'm trying to create.

In Unity I do get the light mask to work somewhat as well if I try using a high poly mesh which is displayed on the right. However I want to use a normal map on a flat plane and there I start to get problems. This is the one one the left: the "light" direction looks pretty correct but I get this weird gradient filling the mesh if I move the empty object on it's Z axis.

This happens even if I swizzle the channels of the normal map around. I created the normal map in Blender with Raw color management.

Here is the shadergraph i'm trying to use, so I just get the Dot Product of the world position of the empty and the normal map. Am I doing something wrong with the graph or is my normal map messed up? Help, i'm a noob :)

Have you tried normalizing both inputs before taking the dot product?


text:
How can I display properties/attributes of an object in an editor?
I'm learning how to make a game engine using SDL and OpenGL and I'm using imgui for the engine editor UI and I'm trying to make a properties panel that displays the properties of the selected object. The code I currently have works although it's extremely basic and I'm realizing that it'll probably become very repetitive the more I add so I'd like to know what I could do to improve.
So I have a base GameElement class and a few test classes that derive from it and I use a GetProperties function to get the values I want to be displayed for the imgui panel
        std::vector<Section> GetProperties() override {
            std::vector<Section> sections;

            // Data
            Section dataSection("Data");
            dataSection.AddProperty(new StringProperty("Name", name));
            dataSection.AddProperty(new BoolProperty("Archivable", archivable));
            sections.push_back(dataSection);

            // Appearance
            Section appearanceSection("Appearance");
            appearanceSection.AddProperty(new Vector3Property("BackgroundColor3", someVector));
            sections.push_back(appearanceSection);

            return sections;
        }

And then in my Editor class I have this which displays the imgui window
    void Editor::Properties() {
        ImGui::Begin("Properties");

        if (selectedElement) {
            auto sections = selectedElement->GetProperties();
            for (auto& section : sections) {
                section.Render();
            }
        }

        ImGui::End();
    }

But yeah the more elements I add and the more properties I start to add to them I'll probably end up with a lot of duplicate code, but since not every element is the same I can't just like make a base class so I'm not sure what I can do here.


text:
Why is my font not found?
Trying to follow this tutorial with using toasts in LIBGDX:
Libgdx - notification popup (something like Toast) - on both Desktop and Android
But i get this error when compiling:
com.badlogic.gdx.utils.GdxRuntimeException: No com.badlogic.gdx.graphics.g2d.BitmapFont registered with name: font-export.fnt

But i have the font in my skin folder with my skin i already use, meaning that the directory is found. I also tried skin/font
com.badlogic.gdx.utils.GdxRuntimeException: No com.badlogic.gdx.graphics.g2d.BitmapFont registered with name: skin/font-export.fnt

Here is the relevant code:
@Override
public void create() {
    sb = new SpriteBatch();
    cam = new OrthographicCamera();
    cam.setToOrtho(false, WIDTH, HEIGHT);
    hudCam = new OrthographicCamera();
    hudCam.setToOrtho(false, WIDTH, HEIGHT);

    gsm = new GameStateManager(this);

    Skin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
    BitmapFont font = Skin.getFont("skin/font-export.fnt");
    toastFactory = new Toast.ToastFactory.Builder()
            .font(font)
            .build();
}

The directiory looks like this:

Well, under what name is the font-export.fnt in your glass-ui.json registered?


text:
Export Animation from Maya to Unity with Segment Scale Compensate
Currently, we are trying to export an animation from Maya which has some joint scale changes during the animation. As you may have encountered before Maya is using Segment Scale Compensate, however, we have already created the animation and don't want to change the working process on Maya.
Is there any way that we can export the animation correctly for Unity? Did anyone encounter this problem?
Thank you

You may get better answers if you can explain what Segment Scale Compensate is doing and what unwanted symptoms you're seeing in Unity after import. That way even users who don't have first hand experience with this specific workflow, but know how to solve analogous problems whose solutions also apply here, can give you the benefit of that insight.


text:
Do texture arrays bring performance gains
I have a terrain mesh in unity that uses a four-layer texture blend, at first I used a single texture (diffuse and normal), then I converted it to two texture arrays storing diffuse and normal respectively. When it runs on an android phone (snapdragon 8gen1), the GPU clock used and the texture read bandwidth have dropped significantly, but the number of times I sample the texture in the shader hasn't changed, so what's happening here?（The bottom image shows the performance data after using an array of textures, and the top shows using a single texture）

It looks like you've answered your own question. "Do they have a performance gain?" — yes, you measured it for this case. Did you mean to ask "WHY or HOW do they improve performance" instead? Those might be good questions for the Computer Graphics StackExchange, since they're about understanding graphics hardware, not about how to develop a game.


text:
Is it possible to launch the default OpenXR runtime app dynamically?
I have a Unity game that I would like to make compatible with VR and desktop both in the same project.
I have a script that calls XRGeneralSettings.Instance.Manager.InitializeLoaderSync(); and XRGeneralSettings.Instance.Manager.StartSubsystems(); when the app launches, as long as no --disable-vr argument was passed.
This script partially works as intended, and it launches into VR, but it requires the active OpenXR runtime (SteamVR, in my case) to be running, else it will fail to initialize.
I would like my app to automatically launch the player's default OpenXR runtime app, rather than having to have them launch it themselves, then launch the game afterwards.
The full script is as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.XR.Management;
public class DynamicOpenXR : MonoBehaviour
{
    private const bool TestingDesktop = false;
    private string[] commandLineArgs;

    public static bool IsInVRMode = false; // This isn't yet used.

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
    void Awake()
    {
        commandLineArgs = TestingDesktop ? new[] { "Nexus.exe", "--disable-vr" } : Environment.GetCommandLineArgs();

        if (commandLineArgs.Contains("--disable-vr", StringComparer.CurrentCultureIgnoreCase))
        {
            Debug.Log("Disable VR command line argument detected. Not enabling VR.");
        }
        else
        {
            Debug.Log("No VR disable argument detected. Initializing OpenXR.");
            StartCoroutine(InitializeOpenXR());
        }

        enabled = false;
    }

    private void OnApplicationQuit()
    {
        if (XRGeneralSettings.Instance.Manager.activeLoader == null) return;

        Debug.Log("Shutting down OpenXR...");
        StartCoroutine(DeinitializeOpenXR());
    }

    IEnumerator DeinitializeOpenXR()
    {
        XRGeneralSettings.Instance.Manager.StopSubsystems();
        yield return null;

        XRGeneralSettings.Instance.Manager.DeinitializeLoader();
    }

    IEnumerator InitializeOpenXR()
    {
        XRGeneralSettings.Instance.Manager.InitializeLoaderSync();
        yield return null;

        while (!XRGeneralSettings.Instance.Manager.isInitializationComplete)
            yield return null;

        XRGeneralSettings.Instance.Manager.StartSubsystems();
        yield return null;
    }
}

Any help is appreciated, thanks!


text:
How to properly overlay HTML over canvas with scaling?
If I have
<div container>
<my html overlay>
<my game canvas>
</div>

The canvas has left: 0; top: 0; width:100%; height:100%; position: relative;. The div container is a certain width and height that adjusts to aspect ratio based on when the user resizes the screen. On resize I set the official size of the canvas (in three.js, renderer.setSize) to the same size to match it up.
This works fine, but then how do I get the html overlay to match the same position it has, over the canvas, when adjusting the size (based on keeping the aspect ratio and scaling in general)?
I think I have to use css scale, but need help in determining what to base the scale factor on.

As far as I can tell, this has nothing to do with game development. You might want to ask this question on StackOverflow or similar platforms.


text:
Ideas for how to attach meta data to an arbitrary sprite sheet?
I am currently messing around with monogame and creating some silly sprite based games. One issue I have is when I get sprites for OpenGameArt or any equivalent they are often in spritesheets in a rather random manner.
For me to parse these spritesheets and actually get the specific sprites, (coordinates on spritesheet, attach them if they are animations, width, height etc), have proven to be a fairly laborous task. Which basically means I have to manually go through each sprite sheet, assign it the relative coordinate in a json file with  all the other meta data. This obviously takes forever and is not a very nice workflow.
So I was wondering is there any sort of way for me to at least detect sprites in a spritesheet? and output those coordinates to a json file? I have been looking around and I cannot really find much of anything.
Thanks!

Does this answer your question? Is there an easier way to get sprites from a spritesheet


text:
Live notifications using PlayFab
I want to integrate live notification, send/receive, in my Unity game using the PlayFab server. Is there an API call for this?

There is a full guide right away at https://learn.microsoft.com/en-us/gaming/playfab/features/engagement/push-notifications/quickstart. Have you taken a look at it and are struggeling with some point?


text:
What are the Godot equivalent to these Unity types and Functions for graphics processing?
Here are some unity types in this script: https://github.com/aras-p/UnityGaussianSplatting/blob/main/package/Runtime/GaussianSplatRenderer.cs
which I am trying to convert to Godot:
ComputeShader //For functions like GetKernelThreadGroupSizes and Dispatch
GraphicsBuffer //For use with the commandbuffer
CommandBuffer //For all sorts of functions from DrawProcedural to ReleaseTemporaryRT
Hash128 //For knowing when to dispose of resources
ProfilerMarker //For profiling
ProfilerCategory //For profiling
MeshTopology //For triangles for drawing
GraphicsFormat //For R16G16B16A16_SFloat
FilterMode //For Point
RTClearFlags //For Color
BuiltInRenderTextureType //For CurrentActive
Graphics //For DrawProcedural
Bounds //For DrawProcedural

Ultimately the Godot compute shaders are described here https://docs.godotengine.org/en/stable/tutorials/shaders/compute_shaders.html but I don't know how to translate this into that. If you could tell me how to translate each of these individual types or just change my entire approach for Godot, either of these would be very helpful. Thanks.


text:
Wrong initial level loaded for packaged build
I am having an issue with Unreal Engine 5.2 initially loading "Temp/Untitled_0" as the level before loading the actual default level that I have set in project settings. I have the editor startup map, the game default map, and server default map set correctly to "MainMenu3D" but when I package my game for windows I have logging that shows that it starts with the Untitled_0 map and then deconstructs my UIManager class which had references that are lost from that point on. I also have the map added to the list of maps for packaging.
The UIManager is initialized in my GameInstance class (GameManagingInstance).
Warning: GameManagingInstance initialized
Warning: UIManager initialized with session parent menu: BP_SessionParent_C in object ID: 22451
Display: Audio Device (ID: 1) registered with world 'Untitled'.
Updating window title bar state: overlay mode, drag disabled, window buttons hidden, title bar hidden
Display: Game Engine Initialized.
Display: Starting Game.
Browse: /Game/Levels/MainMenu3D?Name=Player
LoadMap: /Game/Levels/MainMenu3D?Name=Player
BeginTearingDown for /Temp/Untitled_0
UWorld::CleanupWorld for Untitled, bSessionEnded=true, bCleanupResources=true
InvalidateAllWidgets triggered.  All widgets were invalidated

I also deleted the Binaries, DerivedDataCache, Intermediate, and Saved folders in the project, rebuilt, recooked, and repackaged multiple times with no change.

Looks like you have everything sorted out. I think loading Untitled_0 is just part of Unreal's life cycle. Other people seem to have it too (https://forums.unrealengine.com/t/assertion-failed-file-build-ue4-sync-engine-source-editor-unreleased-private-editorserver-cpp-line-1971-temp-untitled-0-untitled-still-around-while-trying-to-load-new-map-object-is-not-currently-rooted/453041).
Rather than that, look into why your UIManager is being destroyed.


text:
Second player gets stuck while joining
I get this error message on the console whenever I try to make the second player join.

Failed to find a PhotonView with ID=2 for incoming OwnershipUpdate event (newOwnerActorNumber=1), sender=1. If you load scenes, make sure to pause the message queue.


text:
Blinking JLabel for Wordle-like game?
I would like to implement a blinking effect on a JLabel in a wordle knockoff I'm making. I think this will involve using javax.swing.Timer but I'm not sure how I would implement this. The game panel consists of a 5*6 grid (like worlde) of JLabels. I would like them to blink between dark gray and light gray. What should I do? Here is my code so far:
package projects23;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

import javax.swing.*;

public class Wordle {
    File wordList = new File("words.txt");
    File allWords = new File("words.txt");
    JLabel entry[][] = new JLabel[6][5];
    int guessNum = 0;
    int letIndex = 0;
    char lastLetter = ' ';
    String guessArray[] = { "", "", "", "", "" };
    HashMap<Character, Integer> freq = new HashMap<>();
    HashMap<Character, Integer> revert = new HashMap<>();
    String targetWord;
    MyFrame frame;
    KeyListener list;

    Scanner reader;
    Scanner checker;

    public Wordle() {
        pickWord();
        setFreq();
        revert.putAll(freq);
        initGUI();

    }

    private void pickWord() {
        try {
            reader = new Scanner(wordList);
            Random rand = new Random();
            int pick = rand.nextInt(5740);
            for (int i = 0; i < pick; i++) {
                targetWord = reader.nextLine().toUpperCase();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setFreq() {
        int count;
        for (int i = 0; i < 5; i++) {
            count = 0;
            if (freq.containsKey(targetWord.charAt(i))) {
                count = freq.get(targetWord.charAt(i));
                freq.put(targetWord.charAt(i), ++count);
            } else {
                freq.put(targetWord.charAt(i), 1);
            }
        }
    }

    public void initGUI() {
        frame = new MyFrame("Wordle", 500, 600);

        MyPanel title = new MyPanel("Wordle", Color.BLACK);
        frame.add(title, BorderLayout.NORTH);

        MyPanel center = new MyPanel(Color.DARK_GRAY);
        center.setLayout(new GridLayout(6, 5));
        frame.add(center, BorderLayout.CENTER);

        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 5; j++) {
                entry[i][j] = new JLabel("", JLabel.CENTER);
                entry[i][j].setFont(new Font(Font.MONOSPACED, Font.PLAIN, 24));
                entry[i][j].setSize(50, 50);
                entry[i][j].setLocation(i * 50 + 5, j * 50 + 5);
                entry[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK));
                entry[i][j].setBackground(Color.DARK_GRAY);
                entry[i][j].setForeground(Color.WHITE);
                center.add(entry[i][j]);
            }
        }

        frame.addKeyListener(list = new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
                char ch = e.getKeyChar();
                String letter = Character.toString(ch);

                if (e.getExtendedKeyCode() == KeyEvent.VK_BACK_SPACE && letIndex > 0) {
                    letIndex--;
                    guessArray[letIndex] = "";
                    updateGuess("", entry[guessNum][letIndex]);

                } else if (e.getKeyChar() >= KeyEvent.VK_A && e.getKeyChar() <= KeyEvent.VK_Z && letIndex < 5) {
                    guessArray[letIndex] = letter;

                    updateGuess(letter, entry[guessNum][letIndex]);
                    letIndex++;

                } else if (e.getKeyChar() == KeyEvent.VK_ENTER && guessNum <= 5 && letIndex == 5) {
                    String guess = "";
                    for (int i = 0; i < guessArray.length; i++) {
                        guess += guessArray[i];
                    }
                    if (checkValid(guess) == true) {
                        submitGuess(guessArray, freq);
                        freq.putAll(revert);
                        guessNum++;
                        letIndex = 0;
                    }
                }
            }

            @Override
            public void keyPressed(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }

        });

        frame.validate();
    }

    public void updateGuess(String letter, JLabel square) {
        square.setText(letter.toUpperCase());
    }

    private void submitGuess(String[] str, HashMap<Character, Integer> letFreq) {
        String arrToStr = "";
        for (int i = 0; i < str.length; i++) {
            arrToStr += str[i];
        }

        for (int i = 0; i < 5; i++) { // GREEN LETTERS
            entry[guessNum][i].setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
            entry[guessNum][i].setForeground(new Color(235,235,235));
            if (str[i].equals(Character.toString(targetWord.charAt(i)))) {
                letFreq.put(targetWord.charAt(i), letFreq.get(targetWord.charAt(i)) - 1);
                entry[guessNum][i].setBackground(new Color(20, 160, 20));
                entry[guessNum][i].setOpaque(true);
            }
        }

        for (int i = 0; i < 5; i++) { // YELLOW LETTERS
            for (int j = 0; j < 5; j++) {
                if (str[i].equals(Character.toString(targetWord.charAt(j)))
                        && !str[i].equals(Character.toString(targetWord.charAt(i)))
                        && letFreq.get(targetWord.charAt(j)) > 0) {
                    letFreq.put(targetWord.charAt(j), letFreq.get(targetWord.charAt(j)) - 1);
                    entry[guessNum][i].setBackground(new Color(220, 220, 0));
                    entry[guessNum][i].setOpaque(true);
                }
            }
        }

        for (int i = 0; i < 5; i++) {
            guessArray[i] = "";
        }
        frame.validate();

        if (arrToStr.equals(targetWord)) {
            endGame("win");
            frame.removeKeyListener(list);
        }
        if (guessNum == 5 && !arrToStr.equals(targetWord)) {
            endGame("lose");
            frame.removeKeyListener(list);
        }
    }

    private void endGame(String result) {
        Object[] options = { "PLAY AGAIN", "QUIT" };
        int option = JOptionPane.showOptionDialog(null, "You " + result + "! The word was: " + targetWord, "Message",
                JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, null);
        if (option == 0) {
            frame.dispose();
            main(null);
        } else {
            System.exit(0);
        }

    }

    public boolean checkValid(String word) {
        try {
            checker = new Scanner(allWords);
            while (checker.hasNext()) {
                if (checker.nextLine().toUpperCase().equals(word)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        try {
            String laf = UIManager.getCrossPlatformLookAndFeelClassName();
            UIManager.setLookAndFeel(laf);
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Wordle();
            }
        });
    }
}

MyFrame and MyPanel extend jframe and jpanel with some set preferences. The file "words.txt" is the list of possible answer words, and "valid-wordle-words.txt" is all possible 5 letter words (for guesses). If you wanted to test this you could set the target word to any arbitrary 5 letter word and remove the check for a valid word, replace Myframe and MYpanel with JFrame and JPanel (but you may have to set some preferences)


text:
Player controller duplicated or changes position when transitioning from another scene
I am experiencing some weird behavior. I am making a VR game in Unity using OVRPlayerController. I have a menu scene that is a full small level with an OVRPlayerController and when you press a UI element it loads another scene with an OVRPlayerController.
If I load the scenes individually then everything works perfectly - however, when I transition from the menu into the scene - the player controller position is changed. I wrote a script to fix this - however now when I go from the menu, to the scene, and back to the main menu, the player position there is changed. I even tried using a static class to determine if it is the first time the scene is loaded and to position things differently to try and overcome this behavior - but I think maybe I am just misunderstanding something. Is the player controller from the menu scene being taken into the second scene and maybe that is what is causing this weird position shift? When I come back to the menu level, one of the images also doesn't fully load that does load when you first start the game.
I don't understand why the process of loading the level does not simply load it fresh - and I am wondering if some scene state is being carried over even though I haven't specifically programmed that?
Any pointers would be much appreciated!

To help you debug your player controller, we would need to see the code you are using for your controller. To take it to the next scene, a gameobject needs to be marked as DontDestroyOnLoad. If you have one controller per level and you don't destroy it, your code needs to make sure there is only one controller.


text:
Which material property to use when loading models with Assimp
When using Assimp to load models, some mesh materials have only color(COLOR_DIFFUSE, ...) or texture(aiTextureType_DIFFUSE, ...), but some models have both color and texture, which am I supposed to use or how am I supposed to combine the two?


text:
Showing UIDocument controls below appodeal banner in Unity
I use Unity engine for my app.
In one of my scenes I have a single UIDocument, with a root VisualElement containing a few buttons and that buttons aligned to the bottom of it's parent VisualElement container.
Next - I show Appodeal banner at the top of my scene.
The problem is Appodeal banner show itself over my controls in uidocument.
So I want to resize my root VisualElement, containing buttons to place that buttons below Appodeal banner (i.e. AppodealBannerHeight + ButtonsHeight = HeightThatINeed).
I get height for Appodeal banner in onLoaded banner callback.
And I get buttons height via something like myButton.resolvedStyle.height.
But it doesn't work as expected - calculated position is different for landscape and portrait screen orientation and also that position differs for different screen resolutions.
I think I miss something simple.
How I can resolve that issue?


text:
Converting a real-time game with regeneration into a turn-based one?
I'm wanting to make a text-based game, it'll be about managing families like the sims games.
I'm running into innumerable problems with such. One is how to make it turn-based. I know its technically possible to make a real-time text-based games (MUDs do it all the time), but I think that wouldn't work well here due to the sheer number of possible and elaborate commands. On a side note, I'm thinking I'm going to need a text parser for this to give you an idea.
Anyway, in sims-like games the characters have needs that perpetually decay. These have to be re-filled by using furniture items such as beds and fridges and whatnot. Problem is having something like turns last a second would create FAR too many turns for a single in-game day. I was thinking 15-minute turns would be better, though even that's a bit much. Yeah, its silly that it would take 15 minutes to use the toilet, but what can you do? Really the only reason I'm accepting that is because the characters will either be at work/school or sleeping for 2/3 of the day, so that's only at most about 30 commands you'd have to issue per character per in-game day.
The biggest problem really though is differentiating items. In sims games, items come in different tiers, with each restoring your needs at different rates proportional to how much they cost. With 15 minute turns though, it would seem strange for any items to take more than a turn or two to fully fill a need.
I sort of have the same problem with clothing. Yeah, they don't restore stats, but simply ignoring it didn't really feel quite right. The reason I'm bringing this up is that I solved this by having clothing serve different functions. They're distinguished by expense, which affects how easy it is to build relationship scores (higher normally being better of course). They can also be differentiated by function. Do you want to stay warm or cool? How do you want people to perceive this npc? This actually gives a surprising number of options.
With furniture though, the only thing I could think of is to improve environment score (basically, characters are happier the higher this score is, which is based on the items in the room, along with how clean it is). Skill-building items can be distinguished by their effectiveness, but what about items that just restore needs like chairs, stoves, beds, tubs, etc... What, do I need to make it so they have to take a shower for a full 2 hours if they buy the cheapest one? A really big problem is beds, since spending at least 6 or 7 hours in them should all restore your energy to full. Really, I don't recall that number actually mattering in the real game (I haven't been able to play the sims 2 in over 10 years now though, so I can't remember much of that game's mechanics).
How can I do this? Should I just go with the environment score thing? Should I make it so characters don't have a cap on their needs, so more expensive items can push them well above what cheaper items could? Or maybe just make it hard for characters to full max their needs using 'junk' items? Honestly, that could come in handy for certain things, but that could make it hard to play the game when all your characters can only get their needs up to half full.
I really don't know what to do...
edit: Thinking about things I could apply, maybe there is a few things. I could make objects break more often depending on how cheap they are. In light of that, I could also give items a finite lifespan, so they have to be replaced after a while. That could have the added benefit of fixing the issue these games have where there's not much else to do once you have everything. Items that require skills to use could have a cap to what they can do. In the Sims 2 for example, microwaves and toaster ovens could only cook a small portion of the available meals. If you had a high cooking skill, you needed a proper stove to get the most out of it. There's also skill-building items that I already mentioned. This doesn't help with everything though; what about things like chairs and countertops? Countertops in particular in the Sims 2 only really differed in their aesthetic and environment score. Chairs could have different comfort ratings I guess, maybe?
In line with that, I thought maybe it would be fine for some needs to take literal hours to re-fill. If you're 'fun' is bottomed out, maybe you do need to just spend the entire weekend goofing off to refill it before you have to go to work again Monday.
So this leaves me with items that either don't require a skill, don't build a skill, or recover a skill that shouldn't take long to re-fill. Everything else would only have to differ in environment score unless I implemented a breaking mechanic of some sort. Guess that would be fine for countertops and tables and other such things (though tables I guess could differ in how many people can sit at them, but if you can do that why then buy a table with seating for 8 when you can just buy two small tables with seating for 4 each?).
This is getting annoying...

Good work reframing the question as a how-to design question, but I think you could still tighten this further. The section on clothing and furniture doesn't directly relate to discretizing time / regen. If you want help with those aspects, you can post another question focused on them, informed by the answers you get to this question.

Honestly, this question is mostly about furniture. I wasn't sure how to exactly name it. I know the name is sorta misleading, but I couldn't think of a better one.

Maybe the best solution is to break the game down into actions, not turns. Whenever a character is not doing something, the clock would pause and wait for you to enter a command. Then time would pass based on the commands you entered.
For example, let's say your household consists of Joe and Sally. At noon, both of them are inactive. You tell Joe to take a shower; with the particular shower and accessories he has, this will take 30 minutes. However, Sally isn't active, so after giving Joe the "shower" command, the time remains at noon until you give Sally a command.
You tell Sally to check the mail, which takes 7 minutes. Since all members of the household are now busy, time advances forward 7 minutes. Now it's 12:07, Sally is done checking the mail, and Joe has 23 minutes left on his shower.
You tell Sally to make lunch, which will take 25 minutes. Then time advances 23 minutes until Joe is done with his shower; now it's 12:30, and Sally has 2 minutes left until she finishes cooking.
Meters would be updated as actions take place. Let's say that you have a smart speaker to play music in the bathroom. Then Joe would have accrued 30 minutes of entertainment while in the shower. At the same time, his food meter would have depleted by 30 minutes. Luckily, Sally's just about done with lunch, so he'll be able to eat soon.
You tell Joe to get dressed, which will take 5 minutes. The clock advances by 2 minutes, to 12:32, then pauses for you to give Sally a new command (since she just finished cooking). There isn't anything important she can do in the three minutes until Joe's ready, so you tell her to wait for 3 minutes. Now it's 12:35, both characters are ready, and you can tell them to eat lunch.

Comments have been moved to chat; please do not continue the discussion here. Before posting a comment below this one, please review the purposes of comments. Comments that do not request clarification or suggest improvements usually belong as an answer, on [meta], or in [chat]. Comments continuing discussion may be removed.


text:
Cinemachine FreeLookCam stays in "bottom rig" and won't switch to other rigs
I have an issue with Cinemachine. I set it up to follow and look at the "player," and I added the script recommended by another user:
using Cinemachine;
using UnityEngine;
[RequireComponent(typeof(CinemachineFreeLook))]
public class FreeLookUserInput : MonoBehaviour {

    private CinemachineFreeLook freeLookCam;

    void Start () {
        freeLookCam = GetComponent<CinemachineFreeLook>();
    }

    void Update () {
        freeLookCam.m_XAxis.Value = Input.GetAxis("Right Stick X");
        freeLookCam.m_YAxis.Value = Input.GetAxis("Right Stick Y");
    }
}

While I changed the "input" to "SimpleInput" because I'm using it, the problem I can't seem to solve is that when I activate the script, the camera bugs out and stays in the "bottom rig," not allowing me to switch to the other two rigs. I would like to know if anyone knows why this is happening and how I can fix it.
In summary, I need to configure Cinemachine on the secondary joystick to move the camera in any direction while it's locked onto the player.


text:
Get coordinates of clicked point on screen in model space
There is a 2D object located in the coordinate range -1 to 1. In world space, it is also located in these coordinates, but with a shift along the z axis.
The actual initialization of the model, view and projection matrices:
m_model.setToIdentity();
m_view.setToIdentity();
m_projection.setToIdentity();

m_model.translate({0.0, 0.0, -3.0});
m_projection.perspective(38.0, 1.0 * 640 / 480, 0.1, 100.0);

When I click on the rightmost edge of my circle on the screen, I want to get its coordinate, x = 1.0, since r = 1.0.
I have tried several different methods that give the same result, not suitable for me.
1)
    QMatrix4x4 mat = m_view * m_projection * m_model;
    QMatrix4x4 invMat = mat.inverted();
    //NDC x and y
    float pt_x = (p.x()/640.0)*2.0f - 1.0f;
    float pt_y = -(p.y()/480.0)*2.0f + 1.0f;

    QVector4D nearPlane(pt_x,pt_y, -1.0, 1.0);
    QVector4D farPlane(pt_x, pt_y, 1.0, 1.0);
    QVector4D nearRes = invMat * nearPlane;
    QVector4D farRes = invMat * farPlane;
    nearRes /= nearRes.w();
    farRes /= farRes.w();
    QVector3D direc = QVector3D(farRes - nearRes);
    direc.normalize();

    QVector3D screenPos(p.x(),p.y(),1.0f);
    QVector3D vecUnproj = screenPos.unproject(m_view(),m_projection(),QRect(0,0, 640, 480));
    vecUnproj.normalize();

Output:
direc = QVector3D(0.314588, 0, -0.949228)
vecUnproj = QVector3D(0.314589, 0, -0.949228)

As a result, the resulting vector has x = 0.31, and I expected 1.0. And even clicking on the edge of the window gives me a value of about 0.45. I understand that it looks like I am not taking something into account in the transformation or am not doing some other operation.


text:
Sorting layer of wall in top down game 2d
I made tilemap using tiled app.
I try to sort layer so the when the  player is in front of wall he visible and when he is behind the wall then not viable, it's commonsense.
But problem only one line of wall layer is sort by x=0 y=1 z=0 and other line of wall is show player always overlap it. Even when all wall structure is of same layer I made in tiled. How to solve it?

Does this help? Issue with Sorting Layers with an NPC and Tilemap


text:
Concept Shader to achieve such Toon/Graphical Novel look style

Hi to all,
I have no clue how to achieve this kind of style (DallE Ai picture) by having a shader and custom textures applied to a 3D object.
I see an outline (maybe sobel on normals and depth), and a lot of noise which reminds me of some Watercolor shaders. But other than that I have no idea.
I would be grateful for some help/ideas what components a shader should have to make this (I am using Unity HDRP for now)
Cheers!

The closest you will get is with a cell shader, manual generation or photo reduction.


text:
Set depth value in fragment shader
I'm making a simple 2D renderer and I want to avoid redrawing as much as possible.
My Vertex layout has the 2d position and a float depth value.
I want to assign a depth value to each of them after ordering to render them using depth testing and avoid overdraw.
So it will be like this:

Order all the sprites to draw by Y order. (isometric game)
Set a depth value to each of them (like an incrementing int)
Render them.

How can I achieve that?
I read something about gl_FragDepth but I don't know the range of values that I have to set there. Is it from 0 to 1?
These are my vertex/fragment shaders:
#version 330
layout(location=0) in vec2 v_position;
layout(location=1) in vec4 v_color;
layout(location=2) in vec2 v_texcoord;
layout(location=3) in float v_depth;
out vec4 color;
out vec2 uv;
flat out float depth;
void main() {
  gl_Position = vec4(v_position,0,1);
  color = v_color;
  depth = v_depth;
  uv = v_texcoord;
}

#version 330
uniform sampler2D tex0;
flat in float depth;
in vec4 color;
in vec2 uv;
out vec4 out_color;
void main() {
   gl_FragDepth = depth;
   out_color = texture(tex0, uv) * color;
}

Why would you do this in the fragment shader if the depth is determined earlier in the process, at the y-sorting stage? Setting a depth value in the shader disables early z rejection and slows down your rendering, so this is likely not the right solution to your problem. Note that if your sprites have alpha translucency (like soft antialiased edges instead of hard stairstep jaggies along their outlines), that does not play well with z rejection, and can lead to visible fringing or occluded objects disappearing if you try to z-test against translucent occluders.


text:
How can i move actor's bounding box center in relative location in Unreal Engine 5?
This is my situation. I need align the center of the object (it's box) and the center of the scene component. I have only center of the box TVector type or FVector. How can i do it?
FBox Box;

//some shity code

auto Center = Box.GetCenter();

SomeActor->AttachToComponent(SomeUSceneComponent, SomeAttachmentRules)
SomeActor->SetRelativeLocation(??????)

```


text:
Implementing building structures in a text-based game?
Basically, I'm trying to make a text-bases sims-like game. Obviously, making a text version of a graphical game while keeping it actually interesting to play is proving quite difficult.
One of my biggest problems is handling building. Initially, I was thinking of just letting furniture be purchased and just assume the house had room for everything. However, I was hoping to incorporate something equivalent to the legacy and apocalypse challenges for The Sims 2 (they were the ways I preferred to play the game). Problem is, these come with building restrictions that would be hard to ignore.
For instance, the 'middle of nowhere' 'handicap' for the legacy challenge forbids you from placing more than 2 segments of a construction per day. Meaning only 2 wall segments, windows, doors, etc, IN TOTAL per day. It also applies a one-furniture per day restriction, but not having that other feature I think nerfs the handicap too much. The apocalypse challenge is worse, because its NOT an optional feature. No structure in this challenge can be more than 8x8 tiles in size. You are allowed to build upper floors and basements though. I didn't see much point in implementing that latter feature obviously, but as I said it would be hard to ignore this. Its basically the entire part of the 'politics' restriction (a section of rules that must be followed until a character reaches the top of the politics career).
I'm starting to think this thing being 100% text-based is simply not doable. Perhaps it would be better for me to actually have some graphical element to the thing; at least make it so you can plan out structures. Thinking about that, maybe using pygame wouldn't be such a bad idea. I've had innumerable issues with it, but honestly it would probably do fine for a turn-based game. Also, it would make the whole text-based thing easier; I could just erase text and replace it rather than using the 'print' command to go to the next screen. This would also give me the option of having buttons and even using the mouse, which could be handy honestly. Of course, if I do that, what's the point of making the thing text-based? Why not just have it all be graphical? Outside of the fact that I could never hope to make enough assets for such a game even if I could.
Do I need to just add some graphical elements to this thing to some extent? Is there a way I can still do something like this using just text? Could I replace these mechanics with something else that would allow me to dodge having to put BUILDING ELEMENTS IN A TEXT GAME? Maybe I could come up with something else for the politics restriction? Or maybe just change it out for another career with a completely different theme? And what about that legacy handicap? Should I just not implement that? That would be easy, though I would prefer to put another handicap in there to replace it. You can still look up the rules for the Sims 2 Legacy and Apocalypse Challenges if you need to see what they already require. Note that they're not perfectly identical to the sims 3 and sims 4 equivalents, due the games not being identical in mechanics (obviously).
edit: If you don't want to look up the rules, I'll try to summarize things as best I can. In the Legacy challenge for The Sims 2, you're trying to play the game for 10 generations, while trying to accomplish various achievements (for lack of a better word) along the way. Handicaps are optional rules you can choose to follow in exchange for more points in the end. Handicaps always place some sort of restriction on your household in exchange for these extra points. Some handicaps include things like all sims must be fit before they reach adulthood and be obsessed with fitness, they must all share a hobby, you may only issue up to 3 commands to your characters per day, or the most extreme of all you have to play by the apocalypse challenge rules at the same time! If it matters, I was thinking of adding more of my own (namely a handicap called 'infiltration', where every generation must be born via alien abduction, a challenge that the original game doesn't even allow because sims born this way can't be impregnated by aliens themselves, making the chain impossible to continue).
Regarding the apocalypse challenge, it works by locking most of the game's features behind careers. These can include everything from certain social actions to most often furniture items. You unlock things by reaching the top of the game's various careers. The goal is to reach the top of every career and unlock everything. The problem with replacing the restrictions with the politics career is that virtually nothing is allowed at the start already (mainly due to the sheer number of new careers added by the expansions, the challenge was actually made before any of the expansions came out, and only became harder as a consequence). To give you an idea, you're straight not allowed to purchase furniture from most of the categories (for instance, the only items you can purchase that can fill the hygiene need are sinks), you can only use the lowest tiers of certain items, you can't even marry until you've completed at least one career. Point is, literally removing anything else would actually render the challenge impossible to complete. You literally have only the bare necessities and nothing more to complete this challenge. Essentially, politics would have to be implemented as-is, or the whole career just cut from the game in general. Obviously, I'm at an impasse with this.
edit2: thinking about it, I could just remove the handicap for the Legacy mode. This however doesn't solve the problem with the Apocalypse challenge. Still, either way I need to come up with a way to do this in a purely text-based game, add graphics, or find some alternative I can replace it with.
edit3: Thinking about it again, perhaps this simply isn't the best sort of game for this sort of challenge. Why not just make a game specifically designed around rebuilding the world after an apocalypse? This does remove an entire planned game mode from my game, though I was thinking of adding other challenges anyway. It also removes one of the few handicaps that offers more than 1 point to the final score for the Legacy challenge, but oh well. Guess I'll have to add 4 points worth of other handicaps to replace it, and everything will be the effectively the same. Or maybe I could just ignore it entirely. My game won't be a complete clone of the sims 2 anyway, so its not like I'm not having to ditch a few other handicaps and rules anyway.
edit4:Looking over the handicaps for the Legacy challenge, I wouldn't be able to incorporate more than half of them without having buildings. A particularly problematic one is the 'hypochondriac' handicap, which requires one, among many things, to quarantine a sick sim in a single room for a whole week. Not only would I need buildings for this, I would also need a freaking pathfinding algorthm.
I'm beginning to question if this can even be done. It appears the legacy challenge actually needs buildings more than the freaking apocalypse challenge. Maybe I need to make my game and come up with its own equivalent to the legacy and apocalypse challenges. I would need to fully replicate all the functionality of the Sims 2 for me to use these challenges as-is. Aside for the legal issues this may cause (not that I was planning on releasing my game for profit, actually I was just making it so I could play the Sims 2 again). Its not possible to fully replicate all its functions in a text game anyway, and looking over strategy guides the game had far, far more features than I was aware of when I played it. I probably only explored less than half of that game's features despite playing it for years.
Sorry for the tangent, guess I need to just make my own game without trying to figure out how to implement everything from its inspiration, and then come up with my own game modes that are actually fully compatible with it.

Assume readers will not go do research on other sites to understand your question. Try to include any information they need in the body of the question itself.

The problem is, there's so many rules, far too many to post here. The apocalypse challenge in particular is infamous for its ludicrous number of rules. To give you an idea, the game with all its expansions has a grand total of 28 career paths, all of which must be completed to complete the challenge. Each of them has at least a half dozen, sometimes DOZENS of restrictions tied to them. Either way, I guess I could post more info.

Sounds like you might need to do a little more legwork then, boiling this question down to specific criteria for success that we can compare proposed design solutions against.

It's best not to segregate edits behind "edit1/2/3:" headings. They make speed bumps on the way to understanding your question. Instead, you can rewrite the question as a whole, as though you already had those thoughts / included that information as part of the very first draft. If anyone is ever curious about the full blow-by-blow of which words were added when, that's tracked automatically by the site, so you don't need to implement your own labelling.

Either way, I'm clearly getting no answers to this. Besides, as my last edit shows I'm thinking its better if I just make a new Legacy and Apocalypse challenge that is compatible with my game, rather than trying to essentially make it compatible with a mod from another game (they're not technically mods granted, they're just sets of rules you have to follow yourself, but honestly that may be as well be what I'm trying to do).

The big advantage of text-based games is that most of the gameplay happens in the player's head. That means you can often abstract complex game mechanics to a point where they become trivial to design and implement, without it affecting the players suspension of disbelieve.
For example, let's take the furniture building system. How could this mechanic be described in an abstract way?

The player can acquire furniture
The dwellings of the player only has a limited amount of space
Each acquired furniture takes up space, which means that the amount of furniture the player can own is limited.

In a visual game, you would implement that with a 2d (or even 3d) space where players move and place furniture items that must not overlap with each other or with walls. The player is going to need a solid UI to place those things. Pathfinding and adjacency effects might have to be considered. This can be a feature that can get pretty complex to design and implement. And we haven't even talked about the art assets yet.
But in a text-based game, you can get away with a much simpler implementation. You can make "living space" simply a scalar resource.

The dwellings of the player has x units of space
Each piece of furniture takes up y units of space.
By comparing x and y, you can calculate a "crampedness factor" that can be used to affect the sim's quality of life.

Example:
You are living in a tiny (25 m²) apartment.

In your apartment you have:
* Small Bed (2 m²)
* Medium wardrobe (2 m²)
* Wilting Houseplant (1 m²)
* High-tech refrigerator (1 m²)
* Cook-o-matic 2000 stove (1 m²)
* Kitchen counter (2 m² )
* Kitchen sink ( 1 m² )
* Large dining table ( 4 m² )
* Bathtub with shower ( 2 m² )
* Basic Toilet ( 1 m² )
* Basic sink with mirror ( 1 m² )

With 18 / 25 m² occupied by furniture, your apartment feels EXTREMELY CRAMPED to live in.

1 => manage furniture
2 => go furniture shopping
3 => look for a bigger apartment
4 => back

Regarding the "middle of nowhere challenge" and "apocalypse mode": Instead of trying to get as close as possible to the original mechanics from the game you are trying to replicate, it might be better to approach these from a different angle.

What exactly is the fantasy those game modes are supposed to convey?
How can that fantasy be sold in a text-based game?

I have never played The Sims and I never heard of these self-imposed challenges. But I assume that the idea is to simulate a sim trying to survive without human civilization. Instead of looking at this through the lense of the building system, it might be better to take a more holistic view of how such a situation could be represented using all the game mechanics you have available, and not just building. Remember, this is your game. You are not bound to the restrictions of modders or people coming up with self-imposed challenges. You can alter the very foundation of the game to craft the experience you want.
Again, I don't know your game and I don't know your inspiration. But I would imagine that the primary challenge would be that procurement of food and furniture becomes a lot more difficult in such a world, which could be represented with a much higher time investment for doing this.

Yeah, I was already thinking of doing the 'room space' thing you described. Didn't really think about incorprating a 'cramped' mechanic though. I was just going to assume that the 'space' a piece of furniture takes up also includes the minimum space you would need around the object to actually use it. Though I was going to implement a 'storage room' mechanic, where you could designate a room for storage. This would double the effective space you have in that room, but you wouldn't be able to actually make use of any of the furniture in that room until it was moved to a non-storage area.

That said, the point of challanges in the Sims 2 is basically to give you a goal. Normally its a sandbox game with no actual goal in mind. Challenges are meant to help mix up the gameplay, but also often just increase the difficulty. This is the main purpose of the apocalypse challenge; the point was to make it actually hard to complete. It works by forcing you to survive using just a handful of cheap items, and as you progress you can unlock more items to use gradually making things easier. I don't think I've ever actually heard of anyone seriously completing it though.

Also, I admit I was thinking of changing the theme of the challenge. the vanilla challenge's story is that a nuclear plant melted down. I was thinking of changing this to something more interesting to me, such as a nature goddess destroying the world due to humans destroying the environment (this was something I had in mind back when I played the game). Or maybe actually change it to you playing a bunch of cavemen and you're actually trying to discover different techs as you go along. Basically, the story needs to be about unlocking techs over multiple generations in some form.

Another comment, maybe I could do something with the 'middle of nowhere' achievement. The point of it is to make it hard to get things. I could implement that in a different way. I was thinking of having one of the vehicles available be a pick-up truck, so you could have your sims save money by hauling stuff themselves to the house. I could increase the cost of items that are shipped, making it more worthwhile to just fetch stuff yourself. I could also increase the time it actually takes to get to community lots. That would surely be worthwhile.

Dealing with the politics restriction in the apocalypse challenge though is far harder. Like, what does having a government actually do? You don't technically need a government to have laws and enforcement (this was the case in a lot of towns in the old west, and was true in my town for a while until its police force was merged with that of a neighboring town). What do they do mostly? They enact laws and deal with foriegn governments. What effect would that have on everyday life? Its hard to imagine really, at least when it comes to stuff that would be applicable to this game.


text:
UE5; fatal error: CoreMinimal.h: No such file or directory
I am leaning to use UE5 and am following this tutorial : https://www.youtube.com/watch?v=KQgOqyYoHAs
However, when I try to compile a simple pawn class on vscode, I am given the error: "CoreMinimal.h: No such file or directory".
I have tried:

refreshing vscode through UE5

adding UE5's public folder to PATH

Uninstalling and reinstalling both UE5 and vscode

I am out of ideas, I have tried every solution I could find on google.


text:
Complexities regarding starting resources
My text-based game will be a sims clone. I'm having problems though deciding what resources the player should start out with.
I'm wanting to implement a form of the legacy challenge from the Sims 2, but I'm having problems doing so due to the differences between The Sims 2 and my game.
In the vanilla start, you start as a college student and end up with $4800 (the game uses a fictional currency, but obviously you can't type the symbol for that). If you chose the eXtreme start (that IS how its supposed to be spelled), you instead start out as an adult (aka, post-college adult) with $1500. Either way, you have the option of starting with a 'legacy tree' on top of either to these options, meaning you have to plant an orchard tree on your lot at the start and it has to stay there the entire run. This tree costs $1200, so obviously this eats up a lot of cash.
Here are the differences between my game and The Sims 2 that makes this hard to implement:
College isn't a separate 'life stage' like it is in The Sims 2. The reason it was implemented in such an odd way was because it was actually added in an expansion. In my game, college will just be something any adult character can do whenever and as many times as they please. This obviously poses a problem. This means that in my game, you always start as an adult regardless. Going through college also requires you to build up skills. In The Sims 2, pre-made characters always start off with no skills at all regardless of their age. So in the eXtreme start, you're starting not only with less money and no degree, but also no skills. College is also a time for you to make friends, and even find your future spouse. With the eXtreme start, you won't have even that, you're just a blank slate. Obviously, having you start off by default as an adult would be rather problematic. Oh, and you can take back items with you from college in The Sims 2, this also means you actually start off with far more resources since you can easily buy all the furniture your house will use; you just need to pay for the structure itself.
I did think of a way to fix this, but I'm not 100% happy with it. I was thinking of implementing the dorm mechanic The Sims 2 has. Basically, in the vanilla start you start off enrolled and living in a dorm. You also start off with enough money to pay your tuition, so no need to worry about that (in the Sims 2, you actually can't have a job while you're at college, though there are ways to earn money, mostly by getting top grades). Outside of this, to send someone off to college you would need to generate enough funds to pay the tuition over the several years they're going to be there up front (this wasn't a part of the sims 2, despite you starting with a rather generous amount of cash upon arriving at college). This money will go with the sim, and they can spend or mis-spend it as the player sees fit. Things could get complicated if you fail a semester though, since you'll end up staying there longer to get your degree if that happens.
I'm not too happy with this though. It all feels rather clunky. Really, I'm just trying to implement a challenge from another game into mine. Its like I'm trying to make this thing compatible with a mod from another game.
Going to college would probably require quite a huge investment, so it wouldn't be easy to pull off. Also, if you did start with the eXtreme start, that doesn't mean you can't go to college afterwards. In The Sims 2, you can only get one degree, and once you're a full adult you can never apply even if you didn't in the past (that's because you can only sign up to college as a teen, and in the base game they directly aged into adults, this is why the 'young adult' stage had to be implemented in such a weird way). So and eXtreme start founder could still get the degree anyway, and get part of its benefits. Also, the eXtreme start with have a boon; since you're not starting at college, you would start the challenge/game mode in full with a younger character, giving you more time to do things. This is supposed to be a handicap; something you do to make the game harder in exchange for a higher possible final score. At best in my game, it would be more of a trade-off. eXtreme would just mean you don't start off in college, but instead save it for a later date. You would have less starting money to, but this would still be a trade-off rather than a pure detriment.
I don't know what I could do about this. And no, I can't just change the handicap to say your characters can never attend college; many of the possible points you can score require you to do so. This handicap would thus actually reduce your score, by making it impossible to get some of the possible achievements you need to score.
The only way I see to implement this would be to just straight copy how college works in the Sims 2, which was itself kinda wonky. Its sorta a problem with the game; as expansions came out and new features were added the thing ended up being turn into a conglomerate game with multiple conflicting mechanics. There's actually two different skill systems in the game. There's also the hobbies thing which does the same thing as interests but with different nuances, and they both exist side-by-side in the game! Its actually a bit of a mess. I wasn't looking to copy the game whole-sale; I was planning on addressing some of its issues (though most of those would be glitches that don't really alter the gameplay, such as fixing it so you don't corrupt your save if you marry certain npcs).
Oh, and if that's not enough, I wasn't planning having the game spawn you on an empty lot like the Sims 2 does. I was planning on using a pre-made house, just to save the annoyance of having to build the same starting house over and over. I guess I could ditch this and give you a blank lot you could put whatever you want on, but I sorta don't like the annoyance, especially since this game being text-based, it means there isn't really any design; you would just be 'purchasing' rooms with a certain amount of space and items to put in them. The game isn't even going to take into account how the rooms are connected, or how they're shaped, or even if they're on the same floor or not.
The point of this handicap is to make the start harder. You don't have any skills, you did no networking before starting, and you brought nothing back with you and to boot have less money to start with. The legacy tree thing adds another wrinkle, though that could be implemented easily by just lowering your starting money when you get to the lot where you'll actually be building your mansion in exchange for some free food and an extra point in the end. Maybe I could say that if you do the eXtreme start and have the legacy tree, you start off dead broke and essentially live as a homeless person until you make some cash (you COULD in theory do that in my game the way I'm thinking of designing it, though The Sims 2 didn't really let you do that).
How else could I implement this into my game? I'm really at a loss.
What can I do about all this? How do I handle this differing start in a game that doesn't have the wonky aging system The Sims 2 did?

Determining the starting resources most games is a matter of play testing:

Pick some initial value(s)
Play test, noting the impact of choices from step 1.
If needed, revise choices based on impact & repeat step 2.

Since you're taking inspiration from an existing title, using similar starting values might be reasonable. But since you're altering some mechanics, you probably need to tune your starting values differently.
A common tuning heuristic is to use doubling & halving to gradually zero in on good values. For instance, if a value seems too low, double it until it's not. When you over shoot, you have bounded the problem. Once it's bounded you can take the middle between the last "too high" value & the last "not high enough value".
Log the values values as you tune. I suggest keeping them in a CSV type spreadsheet or text file and keeping that in the repository with your code. In the event that you need to roll back, you'll have a set of data that accompanied that version of the project.
In addition the resources parameters, you'll need some indication of how good they were. This is going to vary, but if possible I would suggest something more fine grained than a simple good / bad. You might want to have a subjective five star rating system. You may also want to keep track of how quickly the game reached a win or fail state. There are two reasons I suggest keeping more than just the final good values.
First, the doubling / halving heuristic doesn't account for synergies. Adjusting one resource may unbalance another. If you need to go back and tweak a previously tuned resource, logging a little more data will make it easier to look for things that are in the "vicinity" of previously known good values. It won't remove all the work, but it will give you more to go on than guessing.
The second reason is to address something from your other posts: challenge modes. Tracking the data allows you to move away from ideal starting conditions towards sub-optimal, but still winnable starting conditions. From there you can come up justifications that fit the feel of your game. A realistic game might limit trees due to emerald ash borer outbreaks whereas something less serious might just make a quip about how it was time for all the trees to leave. You can brainstorm the fiction to fit the data and the challenge will still work because you know the parameters are tough, but potentially winnable. This isn't to say you can't develop some challenges story-first. But since you're already collecting playtest data, you may as well leverage it in multiple ways.

Yeah, I was thinking the value would depend on the economics of my game. Sadly, I don't really know what the values found in the Sims 2 mean practically. I never did do the eXtreme start myself. Its also hard to find the in-game pricing so I could just work out the math myself.


text:
Limiting shooting angle only works when facing right
I have a problem with the shooting being limited when the player is turned to the left side. When I set a range from -145 to 145, on the contrary, it does not shoot into this range, but shoots from this range, i.e. -156, -178, 147, 167. I also have a restriction on the right side when the player is turned, everything works fine there.

    public class Weapon : MonoBehaviour
{
    [SerializeField] private float _offset;
    [SerializeField] private GameObject _prefabBullet;
    [SerializeField] private Transform _shootPoint;
    [SerializeField] private GameObject _effect;
    [SerializeField] private float _rightRotation;
    [SerializeField] private float _leftRotation;

    public IEnumerator Shoot()
    {
        Vector3 diference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float rotateZ = Mathf.Atan2(diference.y, diference.x) * Mathf.Rad2Deg;

        if (Camera.main.ScreenToWorldPoint(Input.mousePosition).x < transform.position.x)
        {
            //transform.rotation = Quaternion.Euler(new Vector3(180f, 0f, -rotateZ));
            rotateZ = Mathf.Clamp(rotateZ, -_leftRotation, _leftRotation);  // Ограничиваем угол влево
            transform.rotation = Quaternion.Euler(new Vector3(180f, 0f, -rotateZ));
            Instantiate(_prefabBullet, _shootPoint.position, _shootPoint.rotation);
            Debug.Log("Left" + rotateZ);
        }
        else
        {
            rotateZ = Mathf.Clamp(rotateZ, -_rightRotation, _rightRotation);  // Ограничиваем угол вправо
            transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, rotateZ));
            Instantiate(_prefabBullet, _shootPoint.position, _shootPoint.rotation);
            Debug.Log("Right" + rotateZ);
        }

        var prefEffect = Instantiate(_effect, _shootPoint.position, _shootPoint.rotation);
        yield return new WaitForSeconds(1f);
        Destroy(prefEffect);
    }
}

I'm not good at English, so I translate most words through a translator. I apologize if something is not clear

Just to make sure I've understood, is this correct? You want your character to be able to shoot in a 290 degree arc, centered at the vertical. So 0-145 degrees left OR 0-145 degrees right, but not towards the floor. When you say "-156, -178, 147, 167", do you mean "It moves smoothly from -156 to -178 then jumps to 147 and moves smoothly to 167"? If so, that implies there's a problem on the right side too [but you say "everything works fine" there?]. I'm unclear exactly what behaviour you are seeing.